简体   繁体   中英

What happens after sleeping thread wakes up?

I know the behavior of sleep method in Java. When I call sleep method currently executing thread will stop it's execution and goes in sleep state. While it is sleeping it acquires the lock.

For example if I call sleep method as follows Thread.sleep(50) My Q is what happens after 50ms. It will wake up and directly start executing or it will go in runnable state and wait for CPU to give it a chance to execute? In other words it will go to Runnable state and fight for CPU with other thread.

Please let me know the answer.

It will go into runnable state. There's never a guarantee a thread will be executing at a particular moment. But you can set the thread's priority to give it a better chance at getting CPU time.

It's up to the operating system scheduler. Typically, if the sleep is "sufficiently small" and the thread has enough of its timeslice left, the thread will hold onto the core and resume immediately when the sleep is finished. If the sleep is "too long" (typically around 10ms or more), then the core will be available to do other work and the thread will just be made ready-to-run when the sleep finishes. Depending on relative priorities, a new ready-to-run thread may pre-empt currently-running threads.

Actually it depends on what operation system do you use and different operating systems has different process scheduling algorithms .

Most desktop operating systems are not real-time operating system. There is no guarantee about the precision of the sleep. When you call sleep, the thread is suspended and is not runnable until the requested duration elapses. When it's runnable again, it's up to the scheduler to run the thread again when some execution time is available.

For example, most Linux distros use CFS as default scheduling algorithm CFS uses a concept called "sleeper fairness", which considers sleeping or waiting tasks equivalent to those on the runqueue. So in your case, thread after sleeping will get a comparable share of CPU time.

它将进入可运行状态,并等待CPU给它执行的机会

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