Reputation: 31
If I start a thread:
new Thread(() -> {
while (running) {
try {
Thread.sleep(TimeUnit.MINUTES.toMillis(30));
/* ... */
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
What happens to the thread if the operating system gets suspended (sleep mode, whatever) while the Thread.sleep() is active? Does the thread resume sleeping normally when the OS goes out of sleep?
I'm using Windows 10.
Upvotes: 2
Views: 383
Reputation: 717
When System goes to sleep mode in Windows; a snapshot of the System is taken, meaning states of all the programs are saved. In this example, let's assume that Windows goes into Sleep mode 5 seconds after Thread.sleep is called. Thread.sleep is at 6th second. After 1 hour Windows is opened again and resumes from the snapshot earlier. This means Thread.sleep continues from 6th second.
Upvotes: 0
Reputation: 9786
In this case, as the systems goes into a sleeping mode, also your thread will go to sleep mode. Certainly, the pc going to sleep, has higher order privileges than the thread you launched. This sleep is different than the one you launched. Briefly, the OS creates a snapshot of the running processes and restores it upon wake up.
When the PC sleeps, it practically freezes everything, the same goes with your thread. If it is stopped at 5 minutes of sleep, it will continue from there upon wake up (even if the sleep lasts longer).
Recall that the sleep of particular thread, 30 minutes in your case, makes sense in the context of the particular application. It means that other parts of the application are counting of the fact that your thread will be sleeping exactly 30 minutes. If it wasn't so, that's if your thread continued with the sleep of the 30 minutes, even if the PC is in sleep mode, it means that your process must be still going, which goes in contradiction with the purpose of sleep
.
Upvotes: 4