Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 6c1885e

Browse filesBrowse files
committed
“wait()和sleep()的区别”,修复一点排版错误
1 parent 4491d47 commit 6c1885e
Copy full SHA for 6c1885e

File tree

Expand file treeCollapse file tree

1 file changed

+4
-3
lines changed
Filter options
Expand file treeCollapse file tree

1 file changed

+4
-3
lines changed

‎contents/difference-between-wait-and-sleep.md

Copy file name to clipboardExpand all lines: contents/difference-between-wait-and-sleep.md
+4-3Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,16 +24,17 @@ synchronized (mon) { mon.notify(); }
2424
如果有多个线程在等待(且`synchronized` 锁对象是同一个,如上例中的mon),则可以调用[ `notifyAll` ](http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html#notifyAll%28%29)来唤醒。但是,只有其中一个线程能抢到锁并继续执行(因为 `wait` 的线程都是在 `synchronized` 块内,需要争夺 `synchronized` 锁)。其他的线程会被锁住,直到他们依次获得锁。
2525

2626
再补充几点:
27-
1. `wait` 方法由 `Object` 对象调用(例如:你可以让 `synchronized` 锁对象调用 `wait` ,如上面例子的mon.wait()),而 `sleep` 则由线程调用。
2827

29-
2. `wait` 之后,可能会伪唤醒(`spurious wakeups`)(正在waiting的线程,无故就被唤醒了,如遇到interrupted, timing out等情况)。因此,你需要多设置一些检查,如果不满足实际的运行条件,则继续等待,如下:
28+
- `wait` 方法由 `Object` 对象调用(例如:你可以让 `synchronized` 锁对象调用 `wait` ,如上面例子的mon.wait()),而 `sleep` 则由线程调用。
29+
30+
- `wait` 之后,可能会伪唤醒(`spurious wakeups`)(正在waiting的线程,无故就被唤醒了,如遇到interrupted, timing out等情况)。因此,你需要多设置一些检查,如果不满足实际的运行条件,则继续等待,如下:
3031
```
3132
synchronized {
3233
while (!condition) { mon.wait(); }
3334
}
3435
```
3536

36-
3. 当线程调用 `sleep` 时,并没有释放对象锁,而 `wait` 则释放了对象锁:
37+
- 当线程调用 `sleep` 时,并没有释放对象锁,而 `wait` 则释放了对象锁:
3738
```
3839
synchronized(LOCK) {
3940
Thread.sleep(1000); // LOCK is held

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.