一个关于Java Thread wait(),notify()的实用例(转)

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

Java代码  
  1. /////  
  2. // ProducerConsumer.java  
  3.   
  4. //  
  5. // 这是个很重要的Thread例子。需要注意的是:  
  6. // wait() 必须在synchronized 函数或者代码块里面  
  7. // wait()会让已经获得synchronized 函数或者代码块控制权的Thread暂时休息,并且丧失控制权  
  8. // 这个时候,由于该线程丧失控制权并且进入等待,其他线程就能取得控制权,并且在适当情况下调用notifyAll()来唤醒wait()的线程。  
  9. // 需要注意的是,被唤醒的线程由于已经丧失了控制权,所以需要等待唤醒它的线程结束操作,从而才能重新获得控制权。  
  10. //  
  11. // 所以wait()的确是马上让当前线程丧失控制权,其他的线程可以乘虚而入。  
  12. //  
  13. // 所以wait()的使用,必须存在2个以上线程,而且必须在不同的条件下唤醒wait()中的线程。  
  14. //  
  15. //  
  16. // 以下的例子:  
  17. // ProductStack 是一个生产者跟消费者共享的同步机制,这个机制决定了什么情况生产者要wait(),什么情况消费者要wait()  
  18. // 可以把ProductStack看作一个产品仓库。当产品仓库满的时候,生产者线程需要wait(),从而放弃对产品仓库的控制。  
  19. // 这个时候消费者线程就可以进来了而取得仓库的控制权。一旦消费者消费了产品,那么仓库就不满了。  
  20. // 这个时候消费者线程就要notifyAll()生产者线程,让等待的生产者线程唤醒。  
  21. // 但是生产者被唤醒后不能马上进行生产,因为它在wait()的时候已经丧失了对仓库的控制权,所以就需要等待消费者线程结束操作,  
  22. // 才能重新取得仓库的控制权,再进行生产。  
  23. //  
  24. // 所以特别注意的是,notifyAll()并不是让当前线程马上让出控制权,而只是让其他wait()当中的线程唤醒而已,  
  25. // 所以对不起,尽管我唤醒你,可你必须还是要等我用完仓库才能进来。这点必须清楚。  
  26. //  
  27. // 相反,仓库如果空的时候,消费者线程就会wait(),然后等待生产者线程来生产产品,生产者进程乘虚而入后,让生产者线程生产产品  
  28. // 并且唤醒消费者线程。这个情况跟上面就类似了。  
  29. //  
  30. ///  
  31.   
  32. public class ProducerConsumer {  
  33.   
  34.       public static void main(String[] args) {  
  35.   
  36.            ProductStack ps = new ProductStack();  
  37.   
  38.            Producer p = new Producer(ps, "生产者1");  
  39.   
  40.            Consumer c = new Consumer(ps, "消费者1");  
  41.   
  42.            new Thread(p).start();  
  43.   
  44.            new Thread(c).start();  
  45.   
  46.       }  
  47.   
  48. }  
  49. class Product {  
  50.   
  51.       int id;  
  52.       private String producedBy = "N/A";  
  53.   
  54.       private String consumedBy = "N/A";  
  55.   
  56.       // 构造函数,指明产品ID以及生产者名字。  
  57.   
  58.       Product(int id, String producedBy) {  
  59.   
  60.            this.id = id;  
  61.   
  62.            this.producedBy = producedBy;  
  63.   
  64.       }  
  65.   
  66.       // 消费,需要指明消费者名字  
  67.   
  68.       public void consume(String consumedBy) {  
  69.   
  70.            this.consumedBy = consumedBy;  
  71.   
  72.       }  
  73.   
  74.       public String toString() {  
  75.   
  76.            return "Product : " + id + ", produced by " + producedBy  
  77.   
  78.                       + ", consumed by " + consumedBy;  
  79.   
  80.       }  
  81.   
  82.       public String getProducedBy() {  
  83.   
  84.            return producedBy;  
  85.   
  86.       }  
  87.   
  88.       public void setProducedBy(String producedBy) {  
  89.   
  90.            this.producedBy = producedBy;  
  91.   
  92.       }  
  93.   
  94.       public String getConsumedBy() {  
  95.   
  96.            return consumedBy;  
  97.   
  98.       }  
  99.   
  100.       public void setConsumedBy(String consumedBy) {  
  101.   
  102.            this.consumedBy = consumedBy;  
  103.   
  104.       }  
  105. }  
  106.   
  107. // 这个class就是仓库,是生产者跟消费者共同争夺控制权的同步资源  
  108.   
  109. class ProductStack {  
  110.   
  111.       int index = 0;  
  112.   
  113.       Product[] arrProduct = new Product[6];  
  114.   
  115.       // push使用来让生产者放置产品的  
  116.   
  117.       public synchronized void push(Product product) {  
  118.   
  119.            // 如果仓库满了  
  120.   
  121.            while (index == arrProduct.length) // 这里本来可以用if(),但是如果catch  
  122.   
  123.                                             // exception会出问题,让满的index越界  
  124.   
  125.            {  
  126.   
  127.                  try {  
  128.   
  129.                       // here, "this" means the thread that is using "push"  
  130.   
  131.                       // so in this case it's a producer thread instance.  
  132.   
  133.                       // the BIG difference between sleep() and wait() is, once  
  134.   
  135.                       // wait(),  
  136.   
  137.                       // the thread won't have the lock anymore  
  138.   
  139.                       // so when a producer wait() here, it will lost the lock of  
  140.   
  141.                       // "push()"  
  142.   
  143.                       // While sleep() is still keeping this lock  
  144.   
  145.                       // Important: wait() and notify() should be in "synchronized"  
  146.   
  147.                       // block  
  148.   
  149.                       System.out.println(product.getProducedBy() + " is waiting.");  
  150.   
  151.                       // 等待,并且从这里退出push()  
  152.   
  153.                       wait();  
  154.   
  155.                  } catch (InterruptedException e) {  
  156.   
  157.                       e.printStackTrace();  
  158.   
  159.                  }  
  160.   
  161.            }  
  162.   
  163.            System.out.println(product.getProducedBy() + " sent a notifyAll().");  
  164.   
  165.            // 因为我们不确定有没有线程在wait(),所以我们既然生产了产品,就唤醒有可能等待的消费者,让他们醒来,准备消费  
  166.   
  167.            notifyAll();  
  168.   
  169.            // 注意,notifyAll()以后,并没有退出,而是继续执行直到完成。  
  170.   
  171.            arrProduct[index] = product;  
  172.   
  173.            index++;  
  174.   
  175.            System.out.println(product.getProducedBy() + " 生产了: " + product);  
  176.   
  177.       }  
  178.   
  179.       // pop用来让消费者取出产品的  
  180.   
  181.       public synchronized Product pop(String consumerName) {  
  182.   
  183.            // 如果仓库空了  
  184.   
  185.            while (index == 0) {  
  186.   
  187.                  try {  
  188.   
  189.                       // here will be the consumer thread instance will be waiting ,  
  190.   
  191.                       // because empty  
  192.   
  193.                       System.out.println(consumerName + " is waiting.");  
  194.   
  195.                       // 等待,并且从这里退出pop()  
  196.   
  197.                       wait();  
  198.   
  199.                  } catch (InterruptedException e) {  
  200.   
  201.                       e.printStackTrace();  
  202.   
  203.                  }  
  204.   
  205.            }  
  206.   
  207.            System.out.println(consumerName + " sent a notifyAll().");  
  208.   
  209.            // 因为我们不确定有没有线程在wait(),所以我们既然消费了产品,就唤醒有可能等待的生产者,让他们醒来,准备生产  
  210.   
  211.            notifyAll();  
  212.   
  213.            // 注意,notifyAll()以后,并没有退出,而是继续执行直到完成。  
  214.   
  215.            // 取出产品  
  216.   
  217.            index--;  
  218.   
  219.            Product product = arrProduct[index];  
  220.   
  221.            product.consume(consumerName);  
  222.   
  223.            System.out.println(product.getConsumedBy() + " 消费了: " + product);  
  224.   
  225.            return product;  
  226.   
  227.       }  
  228.   
  229. }  
  230.   
  231. class Producer implements Runnable {  
  232.   
  233.       String name;  
  234.       ProductStack ps = null;  
  235.   
  236.       Producer(ProductStack ps, String name) {  
  237.   
  238.            this.ps = ps;  
  239.   
  240.            this.name = name;  
  241.   
  242.       }  
  243.   
  244.       public void run() {  
  245.   
  246.            for (int i = 0; i < 20; i++) {  
  247.   
  248.                  Product product = new Product(i, name);  
  249.   
  250.                  ps.push(product);  
  251.   
  252.                  try {  
  253.   
  254.                       Thread.sleep((int) (Math.random() * 200));  
  255.   
  256.                  } catch (InterruptedException e) {  
  257.   
  258.                       e.printStackTrace();  
  259.   
  260.                  }  
  261.   
  262.            }  
  263.   
  264.       }  
  265.   
  266. }  
  267.   
  268.   
  269. class Consumer implements Runnable {  
  270.   
  271.       String name;  
  272.       ProductStack ps = null;  
  273.       Consumer(ProductStack ps, String name) {  
  274.   
  275.            this.ps = ps;  
  276.   
  277.            this.name = name;  
  278.   
  279.       }  
  280.   
  281.       public void run() {  
  282.   
  283.            for (int i = 0; i < 20; i++) {  
  284.   
  285.                  Product product = ps.pop(name);  
  286.   
  287.                  try {  
  288.   
  289.                       Thread.sleep((int) (Math.random() * 1000));  
  290.   
  291.                  } catch (InterruptedException e) {  
  292.   
  293.                       e.printStackTrace();  
  294.   
  295.                  }  
  296.   
  297.            }  
  298.   
  299.       }  
  300.   
  301. }  

posted on 2012-04-17 13:39 AlanLiu 阅读(632) 评论(0)  编辑  收藏 所属分类: java


只有注册用户登录后才能发表评论。


网站导航:
 
<2012年4月>
25262728293031
1234567
891011121314
15161718192021
22232425262728
293012345

导航

统计

常用链接

留言簿

随笔分类

随笔档案

搜索

最新评论

阅读排行榜

评论排行榜