I have found this example in reliable source (https://developer.android.com/guide/components/services.html#CreatingStartedService) :
public class HelloIntentService extends IntentService {
public HelloIntentService() {
super("HelloIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
long endTime = System.currentTimeMillis() + 5*1000;
while (System.currentTimeMillis() < endTime) {
synchronized (this) {
try {
wait(endTime - System.currentTimeMillis());
} catch (Exception e) {
}
}
}
}
}
The question is: Why "sleeping" was implemented this way, and not like this:
endTime = System.currentTimeMillis() + 5*1000;
while (System.currentTimeMillis() < endTime) {
try {
Thread.sleep(endTime - System.currentTimeMillis());
} catch (Exception e) {
}
}
The suggested approach is more compact, and there is no any thread that can call 'notify' on this object. Anyway, even if there it was, the program will "go to sleep" again, if time limit was not expired. So what is hidden reason to write more complex and long code to achieve the same result?
I've seen this question Difference between wait() and sleep() , but it has no answer for my question. I also have seen this Using Object.wait(millisec) to simulate sleep , but my question is more specific.
UPDATE
Can't believe that developer.android.com provides different code samples for different languages (in my case, for English and Russian). Maybe it just have not been updated yet..