This blog will introduce the sleep() method in Thread. The content includes:
- Introduction to
sleep() Sleep()example- Comparison of
sleep()andwait()
Introduction to sleep()
sleep() is defined in Thread.java.
sleep() will make the current thread sleep, that is, the current thread will enter the blocked state (sleep) from the running state. sleep() will specify the sleep time, the thread sleep time will be greater than/equal to the sleep time. When the thread is woken up again, it will change from blocked state (sleep) to runnable state, thereby waiting for the CPU to execute.
sleep() example
1 | class ThreadA extends Thread{ |
Results:
1 | t1: 0 |
Start thread t1 in the main thread. After t1 starts, when the calculation i in t1 is divisible by 4, t1 will sleep for 100 milliseconds through Thread.sleep(100).
Comparison of sleep() and wait()
We know that wait() will let the current thread enter the blocked state (wait) from the running state, and also release the synchronization lock. sleep() will make the current thread enter the blocked state (sleep) from the running state.
However, wait() will release the synchronization lock of the object, while sleep() will not release the lock.
Example:
1 | public class SleepDemo { |
Results:
1 | t1: 0 |
Threads t1 and t2 are started in the main thread. t1 and t2 will reference the synchronization lock of the same object in run(), namely synchronized(obj). While t1 is running, although it will call Thread.sleep(100), t2 will not get cpu execution rights, as t1 did not release the synchronous lock of obj!
Note that if we comment out synchronized(obj) and execute the program again, t1 and t2 can be switched to each other.
1 | t1: 0 |