Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Android Threads and Services Threads in Android Threads in Android

Binyamin Friedman
Binyamin Friedman
14,615 Points

Why not just use Thread.sleep() for 10 seconds?

In the video we use this code:

long endTime = System.currentTimeMillis() + 10 * 1000;
        while (System.currentTimeMillis() < endTime) {
            try {
            } catch (InterruptedException e) {
        Log.d(TAG, "Song downloaded");

to wait 10 seconds. Why not just use Thread.sleep(10000)?

Same query.... No answer till now can you please help Ben Jakuben Sir?

2 Answers

Boban Talevski
Boban Talevski
24,793 Points

Note that his initial idea is to not use sleep at all, as he talks about looping until 10 seconds pass. So, to save the cpu a bit, he decides to let the thread sleep for one sec on every loop iteration. Yeah, he could've used a 10 second Thread.sleep without any loops, but I guess it doesn't simulate the case closely enough.

We don't need the thread to sleep for 10 seconds in its "own world", we need the thread to be able to pickup whenever 10 seconds have passed in the "outside real world" so to speak. Which is why we use the current system time + 10 seconds as a condition in the while loop. So, the thread could theoretically go through only say 6 sleeps of 1 second each, but in the "outside real world" 10 seconds have already passed. This could happen for any number of reasons, like there were dozens of threads in the application that each took their turn and our downloading thread didn't get enough "attention" from the OS, so while it did sleep for only 6 seconds in its "own world", it was put "on hold" or something for the rest of the time and 10 "real outside world" seconds have already passed.

Alexander Zola
Alexander Zola
9,027 Points

ive had same thought, but i think it uses thread sleep to explain in which situations u might need this method (dont waste cpu cycles), this spots occurs very often in threadings