NOTE
6.33 Thread.sleep
1. When a thread wakes after sleep. 2. Thread.sleep vs. Object.wait. 3. References.
This is a historical learning note and may contain outdated or incomplete understanding.
1. When Does a Thread Wake Up After sleep Ends?
Thread.Sleep(1000);
Suppose a thread runs the code above at 2020-01-09 22:47:54. Will it immediately continue executing at 2020-01-09 22:47:55?
- Answer
Not necessarily. The code only means that at 2020-01-09 22:47:55 the thread has an opportunity to compete for the CPU. It does not mean that it has already obtained the CPU and started executing.
2. Thread.sleep vs. Object.wait
| sleep | wait | |
|---|---|---|
| Usage | Static method of Thread; call it directly |
Instance method of Object; used together with synchronized |
| Purpose | Pauses the current thread for a specified amount of time | Makes the current thread wait |
| Releases the lock | No | Yes |
| Gives up the CPU | Yes | Yes |
| How it wakes up | Wakes automatically when the time expires | Woken by notify |
Discussion
Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub