Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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 {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        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.

Alex z
Alex z
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