经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Java » 查看文章
线程通信
来源:cnblogs  作者:不要乱摸  时间:2018/10/12 9:49:15  对本文有异议

1.  wait / notify

要想执行 wait() / notify() / notifyAll() 这些方法,必须首先获得对象的监视器

换言之,这些方法必须在 synchronized 中执行

  1. package com.example.demo22;
  2. import java.util.LinkedList;
  3. public class App2 {
  4. public static void main(String[] args) {
  5. final Factory factory = new Factory();
  6. Thread producer = new Thread(new Runnable() {
  7. @Override
  8. public void run() {
  9. try {
  10. while (true) {
  11. factory.offer();
  12. }
  13. } catch (InterruptedException e) {
  14. e.printStackTrace();
  15. }
  16. }
  17. });
  18. Thread consumer = new Thread(new Runnable() {
  19. @Override
  20. public void run() {
  21. try {
  22. while (true) {
  23. factory.take();
  24. }
  25. } catch (InterruptedException e) {
  26. e.printStackTrace();
  27. }
  28. }
  29. });
  30. producer.start();
  31. consumer.start();
  32. }
  33. }
  34. class Factory {
  35. private LinkedList<Object> container = new LinkedList<>();
  36. private Integer capacity = 5;
  37. public synchronized void offer() throws InterruptedException {
  38. while (container.size() == capacity) {
  39. wait();
  40. }
  41. int e = (int) Math.ceil(Math.random() * 100);
  42. container.push(e);
  43. System.out.println("生产" + e);
  44. notify();
  45. }
  46. public synchronized void take() throws InterruptedException {
  47. while (container.size() == 0) {
  48. wait();
  49. }
  50. Object e = container.poll();
  51. System.out.println("消费" + e);
  52. notify();
  53. }
  54. }

2.  Condition  

  1. package com.example.demo22;
  2. import java.util.concurrent.locks.Condition;
  3. import java.util.concurrent.locks.Lock;
  4. import java.util.concurrent.locks.ReentrantLock;
  5. public class App {
  6. public static void main(String[] args) {
  7. final Worker worker = new Worker();
  8. new Thread(new Runnable() {
  9. @Override
  10. public void run() {
  11. for (int i = 0; i < 10; i++) {
  12. worker.red();
  13. }
  14. }
  15. }).start();
  16. new Thread(new Runnable() {
  17. @Override
  18. public void run() {
  19. for (int i = 0; i < 10; i++) {
  20. worker.green();
  21. }
  22. }
  23. }).start();
  24. new Thread(new Runnable() {
  25. @Override
  26. public void run() {
  27. for (int i = 0; i < 10; i++) {
  28. worker.yellow();
  29. }
  30. }
  31. }).start();
  32. }
  33. }
  34. class Worker {
  35. private final Lock lock = new ReentrantLock();
  36. private final Condition conditionA = lock.newCondition();
  37. private final Condition conditionB = lock.newCondition();
  38. private final Condition conditionC = lock.newCondition();
  39. private Integer signal = 1;
  40. public void red() {
  41. lock.lock();
  42. try {
  43. while (signal != 1) {
  44. conditionA.await();
  45. }
  46. System.out.println("Red");
  47. signal = 2;
  48. conditionB.signal();
  49. } catch (InterruptedException e) {
  50. e.printStackTrace();
  51. } finally {
  52. lock.unlock();
  53. }
  54. }
  55. public void green() {
  56. lock.lock();
  57. try {
  58. while (signal != 2) {
  59. conditionB.await();
  60. }
  61. System.out.println("Green");
  62. signal = 3;
  63. conditionC.signal();
  64. } catch (InterruptedException e) {
  65. e.printStackTrace();
  66. } finally {
  67. lock.unlock();
  68. }
  69. }
  70. public void yellow() {
  71. lock.lock();
  72. try {
  73. while (signal != 3) {
  74. conditionC.await();
  75. }
  76. System.out.println("Yellow");
  77. signal = 1;
  78. conditionA.signal();
  79. } catch (InterruptedException e) {
  80. e.printStackTrace();
  81. } finally {
  82. lock.unlock();
  83. }
  84. }
  85. }

3.  wait()

Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object, or some other thread interrupts the current thread, or a certain amount of real time has elapsed.

The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method. The thread then waits until it can re-obtain ownership of the monitor and resumes execution.

调用wait()方法会造成当前线程等待,直到另一个线程调用这个对象的notify()或者notifyAll()方法,或者其它线程打断当前线程,或者时钟周期耗尽。

调用wait()方法必须当前线程首先获得这个对象的监视器。线程释放对象的监视器的所有权,并等待直到另一个线程通知由于这个对象的监视器造成等待的线程来唤醒(通过调用notify()或notifyAll()方法)。线程等待直到它再次获得对象的监视器所有权。

  1. synchronized (obj) {
  2. while (<condition does not hold>)
  3. obj.wait();
  4. ... // Perform action appropriate to condition
  5. }

 4.  notify()

Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation. 

唤醒一个在对象的监视器等待的线程。如果有多个线程等待在该对象的监视器上,它们中的一个会被选中唤醒。这个选中是任意的,并且取决于具体实现。

5.  notifyAll()

Wakes up all threads that are waiting on this object's monitor.

唤醒在该对象的监视器上等待的所有线程

 

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号