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 块或方法中调用来避免边界问题。
简单来说是为了解决潜在的边界条件 (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基础入门-arraylist存储开销
- java基础入门-arraylist存储开销
- Word Search II Leetcode Java
- Java jdbc中Statement,ResultSet,PreparedStatement
- Java中堆内存和栈内存详解
- Java学习-020-Properties 判断是否存在对应的 key 项
- eclipse下出现乱码的问题
- DBCP连接池配置参数说明
- 用SVN下载编译Spring v4.1.6.RELEASE源码导入eclipse
- Interview Q&A - Java中sleep()和wait()有什么区别
- JAVA之关于This的用法
- 剥下“java.lang.OutOfMemoryError: unable to create new native thread”的外衣
- [转] Eclipse 使用 Link 方式进行插件的安装
- java 反射的总结
- java实现简单的QQ登录界面
- 多线程1(java基础)
- java程序设计实训第一天——游戏的初步想法及整体布局
- 5.spring 数据库开发
- Spring LDAP authenticate method with Pooling - UnsupportedOperationException
- Java之数组array和集合list、set、map