Sleep sleep is an incompatibility in android

I found amazing things about Thread.sleep. The thread does not wake up on time. Let me explain. I create an action (no maintenance) and start the thread as shown below.

Thread.sleep(50000); // 50 seconds System.out.println("something"); 

Then I keep the activity in the foreground and off (by pressing the power button). I also registered the file saved in sdcard. What I found After almost 10 minutes Delayed flow 7.35 minutes to print instead of 50 seconds. This is normal? Can I trust Thread.sleep ()?

 16:47:57 ---- START -------- -------- (all are in time) -------- 16:57:07 -- (in time) 16:57:57 -- (in time) 17:05:38 --- (late) 
+2
java android multithreading
source share
3 answers

Can I trust Thread.sleep ()?

You can trust him to behave as directed 1 . But the specification says that hibernation will stop the flow, at least for that number of milliseconds. In some cases, it can stay longer. For example, if a thread with a higher priority needs more work, a thread with a lower priority may not wake from sleep for a long time.


1 - In fact, theoretically, this may not be as indicated. But you did not submit any evidence to support this ...

+2
source share

You can try:

 LockSupport.parkNanos(nanos) 

Or other methods that it provides. This is more accurate.

+1
source share

I found out that when you turn off the screen using the power button, then android sometimes go into sleep mode. The CPU also goes into sleep mode when the screen is off. This Thread.sleep () serum gives a big delay. In my case, my device was in sleep mode for 7.30 minutes, and when I turn on the cpu screen, I wake up and run Thread again. By acquiring Partial_wake_lock, you can hold cpu to fall asleep even when you press the power button (doesn't turn off).

More details

+1
source share

All Articles