Java - Why wait notify and notifyAll called from synchronized block or method in Java
来源:互联网 发布:新淘宝店如何破零销量 编辑:程序博客网 时间:2024/05/21 08:03
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 块或方法中调用来避免边界问题。
- Java - Why wait notify and notifyAll called from synchronized block or method in Java
- wait / notify / notifyAll 和 synchronized method / block
- wait(), notify() and notifyAll() in Java
- java、synchronized、wait()、notify()、notifyAll()
- Java - Why wait, notify and notifyAll is defined in Object Class and not on Thread class
- 【java】线程同步(synchronized,wait,notify,notifyAll)
- java线程同步(synchronized,wait,notify,notifyAll)
- Java多线程之synchronized,wait(),notify(),notifyAll()
- java wait() notify() notifyAll() synchronized关键字总结
- synchronized , wait() , notify() and notifyAll()
- wait(), notify() and notifyAll() in Java - A tutorial
- Java Thread wait, notify and notifyAll Example
- Java 线程wait, notify and notifyAll 示例
- Java线程中的wait, notify and notifyAll
- java wait notify notifyall
- Java中的synchronized、Object.wait()、Object.notify()/notifyAll()原理
- Java中的synchronized、Object.wait()、Object.notify()/notifyAll()原理
- Java中的synchronized、Object.wait()、Object.notify()/notifyAll()原理
- Ajax属性介绍
- OAuth 2.0系列教程(五) 授权
- 第十六周oj刷题——Problem G: E2 驾驭const
- Storm中的process,thread,task和spout对象实例,bolt对象实例
- 输入一串字符,输出单词的个数
- Java - Why wait notify and notifyAll called from synchronized block or method in Java
- [日志处理工作之四]从flume采集的event中提取能被kibana识别的时间戳 and 对比flume与logstash
- SAE稀疏编码机
- 应用退出
- 排序算法笔记
- ant+junit 测试一
- Android 混淆代码总结
- JS中getElementById()、getElementsByName()、getElementsByTagName()_的区别和应用
- CentOS6.3升级GCC到GCC4.8.2