2009年2月17日星期二

一个关于Java线程waite()、notifyAll()的例子

一个Java解决生产者-消费者同步问题的例子,很有参考价值的。

Java代码
  1. /////
  2. // ProducerConsumer.java
  3. //
  4. // 这是个很重要的Thread例子。需要注意的是:
  5. // wait() 必须在synchronized 函数或者代码块里面
  6. // wait()会让已经获得synchronized 函数或者代码块控制权的Thread暂时休息,并且丧失控制权
  7. // 这个时候,由于该线程丧失控制权并且进入等待,其他线程就能取得控制权,并且在适当情况下调用notifyAll()来唤醒wait()的线程。
  8. // 需要注意的是,被唤醒的线程由于已经丧失了控制权,所以需要等待唤醒它的线程结束操作,从而才能重新获得控制权。
  9. //
  10. // 所以wait()的确是马上让当前线程丧失控制权,其他的线程可以乘虚而入。
  11. //
  12. // 所以wait()的使用,必须存在2个以上线程,而且必须在不同的条件下唤醒wait()中的线程。
  13. //
  14. //
  15. // 以下的例子:
  16. // ProductStack 是一个生产者跟消费者共享的同步机制,这个机制决定了什么情况生产者要wait(),什么情况消费者要wait()
  17. // 可以把ProductStack看作一个产品仓库。当产品仓库满的时候,生产者线程需要wait(),从而放弃对产品仓库的控制。
  18. // 这个时候消费者线程就可以进来了而取得仓库的控制权。一旦消费者消费了产品,那么仓库就不满了。
  19. // 这个时候消费者线程就要notifyAll()生产者线程,让等待的生产者线程唤醒。
  20. // 但是生产者被唤醒后不能马上进行生产,因为它在wait()的时候已经丧失了对仓库的控制权,所以就需要等待消费者线程结束操作,
  21. // 才能重新取得仓库的控制权,再进行生产。
  22. //
  23. // 所以特别注意的是,notifyAll()并不是让当前线程马上让出控制权,而只是让其他wait()当中的线程唤醒而已,
  24. // 所以对不起,尽管我唤醒你,可你必须还是要等我用完仓库才能进来。这点必须清楚。
  25. //
  26. // 相反,仓库如果空的时候,消费者线程就会wait(),然后等待生产者线程来生产产品,生产者进程乘虚而入后,让生产者线程生产产品
  27. // 并且唤醒消费者线程。这个情况跟上面就类似了。
  28. //
  29. ///
  30. public class ProducerConsumer {
  31. public static void main(String[] args) {
  32. ProductStack ps = new ProductStack();
  33. Producer p = new Producer(ps, "生产者1");
  34. Consumer c = new Consumer(ps, "消费者1");
  35. new Thread(p).start();
  36. new Thread(c).start();
  37. }
  38. }
  39. class Product {
  40. int id;
  41. private String producedBy = "N/A";
  42. private String consumedBy = "N/A";
  43. // 构造函数,指明产品ID以及生产者名字。
  44. Product(int id, String producedBy) {
  45. this.id = id;
  46. this.producedBy = producedBy;
  47. }
  48. // 消费,需要指明消费者名字
  49. public void consume(String consumedBy) {
  50. this.consumedBy = consumedBy;
  51. }
  52. public String toString() {
  53. return "Product : " + id + ", produced by " + producedBy
  54. + ", consumed by " + consumedBy;
  55. }
  56. public String getProducedBy() {
  57. return producedBy;
  58. }
  59. public void setProducedBy(String producedBy) {
  60. this.producedBy = producedBy;
  61. }
  62. public String getConsumedBy() {
  63. return consumedBy;
  64. }
  65. public void setConsumedBy(String consumedBy) {
  66. this.consumedBy = consumedBy;
  67. }
  68. }
  69. // 这个class就是仓库,是生产者跟消费者共同争夺控制权的同步资源
  70. class ProductStack {
  71. int index = 0;
  72. Product[] arrProduct = new Product[6];
  73. // push使用来让生产者放置产品的
  74. public synchronized void push(Product product) {
  75. // 如果仓库满了
  76. while (index == arrProduct.length) // 这里本来可以用if(),但是如果catch
  77. // exception会出问题,让满的index越界
  78. {
  79. try {
  80. // here, "this" means the thread that is using "push"
  81. // so in this case it's a producer thread instance.
  82. // the BIG difference between sleep() and wait() is, once
  83. // wait(),
  84. // the thread won't have the lock anymore
  85. // so when a producer wait() here, it will lost the lock of
  86. // "push()"
  87. // While sleep() is still keeping this lock
  88. // Important: wait() and notify() should be in "synchronized"
  89. // block
  90. System.out.println(product.getProducedBy() + " is waiting.");
  91. // 等待,并且从这里退出push()
  92. wait();
  93. } catch (InterruptedException e) {
  94. e.printStackTrace();
  95. }
  96. }
  97. System.out.println(product.getProducedBy() + " sent a notifyAll().");
  98. // 因为我们不确定有没有线程在wait(),所以我们既然生产了产品,就唤醒有可能等待的消费者,让他们醒来,准备消费
  99. notifyAll();
  100. // 注意,notifyAll()以后,并没有退出,而是继续执行直到完成。
  101. arrProduct[index] = product;
  102. index++;
  103. System.out.println(product.getProducedBy() + " 生产了: " + product);
  104. }
  105. // pop用来让消费者取出产品的
  106. public synchronized Product pop(String consumerName) {
  107. // 如果仓库空了
  108. while (index == 0) {
  109. try {
  110. // here will be the consumer thread instance will be waiting ,
  111. // because empty
  112. System.out.println(consumerName + " is waiting.");
  113. // 等待,并且从这里退出pop()
  114. wait();
  115. } catch (InterruptedException e) {
  116. e.printStackTrace();
  117. }
  118. }
  119. System.out.println(consumerName + " sent a notifyAll().");
  120. // 因为我们不确定有没有线程在wait(),所以我们既然消费了产品,就唤醒有可能等待的生产者,让他们醒来,准备生产
  121. notifyAll();
  122. // 注意,notifyAll()以后,并没有退出,而是继续执行直到完成。
  123. // 取出产品
  124. index--;
  125. Product product = arrProduct[index];
  126. product.consume(consumerName);
  127. System.out.println(product.getConsumedBy() + " 消费了: " + product);
  128. return product;
  129. }
  130. }
  131. class Producer implements Runnable {
  132. String name;
  133. ProductStack ps = null;
  134. Producer(ProductStack ps, String name) {
  135. this.ps = ps;
  136. this.name = name;
  137. }
  138. public void run() {
  139. for (int i = 0; i < 20; i++) {
  140. Product product = new Product(i, name);
  141. ps.push(product);
  142. try {
  143. Thread.sleep((int) (Math.random() * 200));
  144. } catch (InterruptedException e) {
  145. e.printStackTrace();
  146. }
  147. }
  148. }
  149. }
  150. class Consumer implements Runnable {
  151. String name;
  152. ProductStack ps = null;
  153. Consumer(ProductStack ps, String name) {
  154. this.ps = ps;
  155. this.name = name;
  156. }
  157. public void run() {
  158. for (int i = 0; i < 20; i++) {
  159. Product product = ps.pop(name);
  160. try {
  161. Thread.sleep((int) (Math.random() * 1000));
  162. } catch (InterruptedException e) {
  163. e.printStackTrace();
  164. }
  165. }
  166. }
  167. }

没有评论:

发表评论