原文链接:http://www.cnblogs.com/dolphin0520/p/3920385.html

在前面我们将了很多关于同步的问题,然而在现实中,需要线程之间的协作。比如说最经典的生产者-消费者模型:当队列满时,生产者需要等待队列有空间才能继续往里面放入商品,而在等待的期间内,生产者必须释放对临界资源(即队列)的占用权。因为生产者如果不释放对临界资源的占用权,那么消费者就无法消费队列中的商品,就不会让队列有空间,那么生产者就会一直无限等待下去。因此,一般情况下,当队列满时,会让生产者交出对临界资源的占用权,并进入挂起状态。然后等待消费者消费了商品,然后消费者通知生产者队列有空间了。同样地,当队列空时,消费者也必须等待,等待生产者通知它队列中有商品了。这种互相通信的过程就是线程间的协作。今天我们就来探讨一下Java中线程协作的最常见的两种方式:利用Object.wait()、Object.notify()和使用Condition

一.wait()、notify()和notifyAll()

wait()、notify()和notifyAll()是Object类中的方法:

  1. /**
  2. * Wakes up a single thread that is waiting on this object's
  3. * monitor. If any threads are waiting on this object, one of them
  4. * is chosen to be awakened. The choice is arbitrary and occurs at
  5. * the discretion of the implementation. A thread waits on an object's
  6. * monitor by calling one of the wait methods
  7. */
  8. public final native void notify();
  9.  
  10. /**
  11. * Wakes up all threads that are waiting on this object's monitor. A
  12. * thread waits on an object's monitor by calling one of the
  13. * wait methods.
  14. */
  15. public final native void notifyAll();
  16.  
  17. /**
  18. * Causes the current thread to wait until either another thread invokes the
  19. * {@link java.lang.Object#notify()} method or the
  20. * {@link java.lang.Object#notifyAll()} method for this object, or a
  21. * specified amount of time has elapsed.
  22. * <p>
  23. * The current thread must own this object's monitor.
  24. */
  25. public final native void wait(long timeout) throws InterruptedException;

从这三个方法的文字描述可以知道以下几点信息:

  1)wait()、notify()和notifyAll()方法是本地方法,并且为final方法,无法被重写。

  2)调用某个对象的wait()方法能让当前线程阻塞,并且当前线程必须拥有此对象的monitor(即锁)

  3)调用某个对象的notify()方法能够唤醒一个正在等待这个对象的monitor的线程,如果有多个线程都在等待这个对象的monitor,则只能唤醒其中一个线程;

  4)调用notifyAll()方法能够唤醒所有正在等待这个对象的monitor的线程;

有朋友可能会有疑问:为何这三个不是Thread类声明中的方法,而是Object类中声明的方法(当然由于Thread类继承了Object类,所以Thread也可以调用者三个方法)?

其实这个问题很简单,由于每个对象都拥有monitor(即锁),所以让当前线程等待某个对象的锁,当然应该通过这个对象来操作了。

而不是用当前线程来操作,因为当前线程可能会等待多个线程的锁,如果通过线程来操作,就非常复杂了。

上面已经提到,如果调用某个对象的wait()方法,当前线程必须拥有这个对象的monitor(即锁),因此调用wait()方法必须在同步块或者同步方法中进行(synchronized块或者synchronized方法)。

  调用某个对象的wait()方法,相当于让当前线程交出此对象的monitor,然后进入等待状态,等待后续再次获得此对象的锁(Thread类中的sleep方法使当前线程暂停执行一段时间,从而让其他线程有机会继续执行,但它并不释放对象锁);

  notify()方法能够唤醒一个正在等待该对象的monitor的线程,当有多个线程都在等待该对象的monitor的话,则只能唤醒其中一个线程,具体唤醒哪个线程则不得而知。

  同样地,调用某个对象的notify()方法,当前线程也必须拥有这个对象的monitor,因此调用notify()方法必须在同步块或者同步方法中进行(synchronized块或者synchronized方法)。

  nofityAll()方法能够唤醒所有正在等待该对象的monitor的线程,这一点与notify()方法是不同的。

  这里要注意一点:notify()和notifyAll()方法只是唤醒等待该对象的monitor的线程,并不决定哪个线程能够获取到monitor。

  举个简单的例子:假如有三个线程Thread1、Thread2和Thread3都在等待对象objectA的monitor,此时Thread4拥有对象objectA的monitor,当在Thread4中调用objectA.notify()方法之后,Thread1、Thread2和Thread3只有一个能被唤醒。注意,被唤醒不等于立刻就获取了objectA的monitor。假若在Thread4中调用objectA.notifyAll()方法,则Thread1、Thread2和Thread3三个线程都会被唤醒,至于哪个线程接下来能够获取到objectA的monitor就具体依赖于操作系统的调度了。

  上面尤其要注意一点,一个线程被唤醒不代表立即获取了对象的monitor,只有等调用完notify()或者notifyAll()并退出synchronized块,释放对象锁后,其余线程才可获得锁执行。

下面看一个例子就明白了:

  1. public class Test {
  2. public static Object object = new Object();
  3. public static void main(String[] args) {
  4. Thread1 thread1 = new Thread1();
  5. Thread2 thread2 = new Thread2();
  6.  
  7. thread1.start();
  8.  
  9. try {
  10. Thread.sleep(200);
  11. } catch (InterruptedException e) {
  12. e.printStackTrace();
  13. }
  14.  
  15. thread2.start();
  16. }
  17.  
  18. static class Thread1 extends Thread{
  19. @Override
  20. public void run() {
  21. synchronized (object) {
  22. try {
  23. object.wait();
  24. } catch (InterruptedException e) {
  25. }
  26. System.out.println("线程"+Thread.currentThread().getName()+"获取到了锁");
  27. }
  28. }
  29. }
  30.  
  31. static class Thread2 extends Thread{
  32. @Override
  33. public void run() {
  34. synchronized (object) {
  35. object.notify();
  36. System.out.println("线程"+Thread.currentThread().getName()+"调用了object.notify()");
  37. }
  38. System.out.println("线程"+Thread.currentThread().getName()+"释放了锁");
  39. }
  40. }
  41. }

无论运行多少次,运行结果必定是:

  1. 线程Thread-1调用了object.notify()
  2. 线程Thread-1释放了锁
  3. 线程Thread-0获取到了锁

二.Condition

  Condition是在java 1.5中才出现的,它用来替代传统的Object的wait()、notify()实现线程间的协作,相比使用Object的wait()、notify(),使用Condition1的await()、signal()这种方式实现线程间协作更加安全和高效。因此通常来说比较推荐使用Condition,在阻塞队列那一篇博文中就讲述到了,阻塞队列实际上是使用了Condition来模拟线程间协作。

  • Condition是个接口,基本的方法就是await()和signal()方法;
  • Condition依赖于Lock接口,生成一个Condition的基本代码是lock.newCondition()
  • 调用Condition的await()和signal()方法,都必须在lock保护之内,就是说必须在lock.lock()和lock.unlock之间才可以使用

  Conditon中的await()对应Object的wait();

  Condition中的signal()对应Object的notify();

  Condition中的signalAll()对应Object的notifyAll()。

三.生产者-消费者模型的实现

1.使用Object的wait()和notify()实现:

  1. public class Test {
  2. private int queueSize = 10;
  3. private PriorityQueue<Integer> queue = new PriorityQueue<Integer>(queueSize);
  4.  
  5. public static void main(String[] args) {
  6. Test test = new Test();
  7. Producer producer = test.new Producer();
  8. Consumer consumer = test.new Consumer();
  9.  
  10. producer.start();
  11. consumer.start();
  12. }
  13.  
  14. class Consumer extends Thread{
  15.  
  16. @Override
  17. public void run() {
  18. consume();
  19. }
  20.  
  21. private void consume() {
  22. while(true){
  23. synchronized (queue) {
  24. while(queue.size() == 0){
  25. try {
  26. System.out.println("队列空,等待数据");
  27. queue.wait();
  28. } catch (InterruptedException e) {
  29. e.printStackTrace();
  30. queue.notify();
  31. }
  32. }
  33. queue.poll(); //每次移走队首元素
  34. queue.notify();
  35. System.out.println("从队列取走一个元素,队列剩余"+queue.size()+"个元素");
  36. }
  37. }
  38. }
  39. }
  40.  
  41. class Producer extends Thread{
  42.  
  43. @Override
  44. public void run() {
  45. produce();
  46. }
  47.  
  48. private void produce() {
  49. while(true){
  50. synchronized (queue) {
  51. while(queue.size() == queueSize){
  52. try {
  53. System.out.println("队列满,等待有空余空间");
  54. queue.wait();
  55. } catch (InterruptedException e) {
  56. e.printStackTrace();
  57. queue.notify();
  58. }
  59. }
  60. queue.offer(1); //每次插入一个元素
  61. queue.notify();
  62. System.out.println("向队列取中插入一个元素,队列剩余空间:"+(queueSize-queue.size()));
  63. }
  64. }
  65. }
  66. }
  67. }

2.使用Condition实现

  1. public class Test {
  2. private int queueSize = 10;
  3. private PriorityQueue<Integer> queue = new PriorityQueue<Integer>(queueSize);
  4. private Lock lock = new ReentrantLock();
  5. private Condition notFull = lock.newCondition();
  6. private Condition notEmpty = lock.newCondition();
  7.  
  8. public static void main(String[] args) {
  9. Test test = new Test();
  10. Producer producer = test.new Producer();
  11. Consumer consumer = test.new Consumer();
  12.  
  13. producer.start();
  14. consumer.start();
  15. }
  16.  
  17. class Consumer extends Thread{
  18.  
  19. @Override
  20. public void run() {
  21. consume();
  22. }
  23.  
  24. private void consume() {
  25. while(true){
  26. lock.lock();
  27. try {
  28. while(queue.size() == 0){
  29. try {
  30. System.out.println("队列空,等待数据");
  31. notEmpty.await();
  32. } catch (InterruptedException e) {
  33. e.printStackTrace();
  34. }
  35. }
  36. queue.poll(); //每次移走队首元素
  37. notFull.signal();
  38. System.out.println("从队列取走一个元素,队列剩余"+queue.size()+"个元素");
  39. } finally{
  40. lock.unlock();
  41. }
  42. }
  43. }
  44. }
  45.  
  46. class Producer extends Thread{
  47.  
  48. @Override
  49. public void run() {
  50. produce();
  51. }
  52.  
  53. private void produce() {
  54. while(true){
  55. lock.lock();
  56. try {
  57. while(queue.size() == queueSize){
  58. try {
  59. System.out.println("队列满,等待有空余空间");
  60. notFull.await();
  61. } catch (InterruptedException e) {
  62. e.printStackTrace();
  63. }
  64. }
  65. queue.offer(1); //每次插入一个元素
  66. notEmpty.signal();
  67. System.out.println("向队列取中插入一个元素,队列剩余空间:"+(queueSize-queue.size()));
  68. } finally{
  69. lock.unlock();
  70. }
  71. }
  72. }
  73. }
  74. }

14 线程间协作的两种方式:wait、notify、notifyAll和Condition的更多相关文章

  1. 多线程之线程间协作的两种方式:wait、notify、notifyAll和Condition

    Java并发编程:线程间协作的两种方式:wait.notify.notifyAll和Condition 在前面我们将了很多关于同步的问题,然而在现实中,需要线程之间的协作.比如说最经典的生产者-消费者 ...

  2. 19、Java并发编程:线程间协作的两种方式:wait、notify、notifyAll和Condition

    Java并发编程:线程间协作的两种方式:wait.notify.notifyAll和Condition 在前面我们将了很多关于同步的问题,然而在现实中,需要线程之间的协作.比如说最经典的生产者-消费者 ...

  3. Java并发编程:线程间协作的两种方式:wait、notify、notifyAll和Condition

    Java并发编程:线程间协作的两种方式:wait.notify.notifyAll和Condition 在前面我们将了很多关于同步的问题,然而在现实中,需要线程之间的协作.比如说最经典的生产者-消费者 ...

  4. 线程间协作的两种方式:wait、notify、notifyAll和Condition

    转载自海子: 在前面我们将了很多关于同步的问题,然而在现实中,需要线程之间的协作.比如说最经典的生产者-消费者模型:当队列满时,生产者需要等待队列有空间才能继续往里面放入商品,而在等待的期间内,生产者 ...

  5. Java并发--线程间协作的两种方式:wait、notify、notifyAll和Condition

    在前面我们将了很多关于同步的问题,然而在现实中,需要线程之间的协作.比如说最经典的生产者-消费者模型:当队列满时,生产者需要等待队列有空间才能继续往里面放入商品,而在等待的期间内,生产者必须释放对临界 ...

  6. Java并发编程(十三)线程间协作的两种方式:wait、notify、notifyAll和Condition

    在现实中,需要线程之间的协作.比如说最经典的生产者-消费者模型:当队列满时,生产者需要等待队列有空间才能继续往里面放入商品,而在等待的期间内,生产者必须释放对临界资源(即队列)的占用权.因为生产者如果 ...

  7. Linux线程间同步的几种方式

    信号量 信号量强调的是线程(或进程)间的同步:"信号量用在多线程多任务同步的,一个线程完成了某一个动作就通过信号量告诉别的线程,别的线程再进行某些动作(大家都在sem_wait的时候,就阻塞 ...

  8. VC 线程间通信的三种方式

    1.使用全局变量(窗体不适用)     实现线程间通信的方法有很多,常用的主要是通过全局变量.自定义消息和事件对象等来实现的.其中又以对全局变量的使用最为简洁.该方法将全局变量作为线程监视的对象,并通 ...

  9. 【转】VC 线程间通信的三种方式

    原文网址:http://my.oschina.net/laopiao/blog/94728 1.使用全局变量(窗体不适用)      实现线程间通信的方法有很多,常用的主要是通过全局变量.自定义消息和 ...

随机推荐

  1. 前端与HTTP

    本文整理在,我的github 上.欢迎Star. 各版本的http 发展 在HTTP建立之初,主要是为了传输超文本标记语言(HTML)文档.随着时代的发展,也进行了若干次演进.下图是各个版本发布的时间 ...

  2. CentOS 7更换yum源

    1. 首先备份 sudo mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.backup 2. 使用阿里云的 ...

  3. CentOS 新系统后配置

    1. 网络配置 略 1.2 ip_froward 查看 sysctl -a | grep ip_ 修改 vi /etc/sysctl.conf net.ipv4.ip_forward = 1 最大使用 ...

  4. Centos7 Minni 安装 执行ifconfig命令出现 -bash ifconfig command not found 的解决方法

    1) have a root privilege shell or be on the sudo list. 2a) At a root shell prompt (#) yum install ne ...

  5. 模拟远程HTTP的POST请求

    建立请求,以模拟远程HTTP的POST请求方式构造并获取处理结果 /// <summary> /// 建立请求,以模拟远程HTTP的POST请求方式构造并获取处理结果 /// </s ...

  6. SelectOnCheck

    1.checkOnSelect 如果为true,当用户点击行的时候该复选框就会被选中或取消选中. 如果为false,当用户仅在点击该复选框的时候才会呗选中或取消. 2.selectOnCheck 如果 ...

  7. web 给大家分享一个好玩的东西,也许你那块就用的到

    先看效果: 就这个效果.当你点击右上角的删除按钮,会删除掉item1. 上代码: <!DOCTYPE html> <html> <head> <meta ch ...

  8. Oracle.DataAccess.dll方式操作oracle数据库

    Oracle.DataAccess.dll方式操作oracle数据库 一.查询语句: using (OracleConnection conn = new OracleConnection(Syste ...

  9. Android 如何保存资源 Id 数组在 res/values/arrays.xml 里

    <resources> <!-- Tracks Information --> <array name="music_ids"> <ite ...

  10. 【git】——简单用法

    git 更新远程代码到本地 git fetch origin master git merge origin/master 冲突: Your local changes to the followin ...