您的位置:首页 > 编程语言 > Java开发

Java - Why wait notify and notifyAll called from synchronized block or method in Java

2015-06-29 17:11 696 查看
http://javarevisited.blogspot.de/2011/05/wait-notify-and-notifyall-in-java.html

简单来说是为了解决潜在的边界条件 (race condition) 问题。

用分步的生产者消费者流程举例来说:

1. The Producer thread tests the condition (buffer is full or not) and confirms that it must wait (after finding buffer is full). 即生产者线程在调用wait方法之前暂停了,轮到消费者线程运行。

2. The Consumer thread sets the condition after consuming an element from buffer.

3. The Consumer thread calls the notify () method; this goes unheard since the Producer thread is not yet waiting. 因为生产者线程还没来得及调用wait,所以这时候消费者发出的notification并不能被生产者线程接收到。

4. The Producer thread calls the wait () method and goes into waiting state.

所以由于race condition,这里我们丢失了一个notification, 当我们使用buffer或者只有一个element的队列时,生产者线程就会处于永久的等待中。

所以要在同步块或同步方法中调用wait, notify, notifyAll, 这样可以保证checking the condition (buffer is full or not) 和setting the condition (taking element from buffer) 的操作是原子的,从而避免边界问题。

另外,如果没有在同步块或同步方法中调用的话,Java 是会抛出 IllegalMonitorStateException 异常的。

synchronized 和 wait notify 是两个不同的area。 synchronized 是为了保证线程安全, wait notify 是两个线程间的通信机制。

wait notify一般都在synchronized 块或方法中调用来避免边界问题。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: