简体   繁体   中英

Thread sleep is inconsistance in android

I found a surprising things about Thread.sleep. Thread doesn't wake up in time. Let me explain. I create an activity (no service) and run a thread like the following.

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

Then i keep the activity in foreground and off the display (by pressing power button). Also i was logging in a file saved in sdcard. What i found that, After almost 10 min Thread delay 7.35 minutes to print instead of 50 seconds. Is it normal?? Can i trust on Thread.sleep()?

16:47:57 ---- START
-------- 
-------- (all are in time)
--------
16:57:07 -- (in time)
16:57:57 -- (in time)
17:05:38 --- (late)

Can i trust on Thread.sleep()?

You can trust it to behave as specified 1 . But the specification says that a sleep will cause the thread to stop for at least that number of milliseconds. Under some circumstances, it could stop for longer. For example, if there is a lot of work for a higher priority thread to do, a lower priority thread may not be woken from the sleep for a long time.


1 - Actually, in theory, it might not behave as specified. But you've tendered no evidence to support that ...

You can try:

LockSupport.parkNanos(nanos)

Or other methods it provides. It's more accurate.

I found out that when you turn off the screen using power button then android go to sleep after sometimes. CPU also go to sleep when screen is off. That's whey Thread.sleep() is giving large delay. In my case my device was in sleep mode for 7.30 minute and when i turn on the screen cpu wake up and start the Thread again. By acquiring the Partial_wake_lock you can hold cpu to go to sleep even when you press the power button(not shutdown).

More details

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM