• 那是从何处传来的钟声呢?偶尔听到那钟声,平添一份喜悦与向往之情。

Java线程生产者和消费者实例

后端 Nanait 12年前 (2012-08-06) 953次浏览 已收录 0个评论 扫描二维码

代码如下

  1. /*
  2.  *
  3.  * 
  4.  * 
  5.  * 细节: 判断仓库有否有货是否,必须用 while,而不能用 if,作用是让线程醒过来的时候,还要判断是否为空,如果用 if 的话,就不会判断,直接往下走,会导致连续生产或者消费
  6.  *            超过两个线程的时候,用 notifyAll 唤醒,不要用 notify
  7.  *      
  8.  *
  9.  */
  10. class Resource {
  11.     private String name;
  12.     private int id=1;
  13.     private boolean isEmpty = true;
  14.     public synchronized void put(String name) { //生产
  15.         //如果不是空,就 wait()
  16.         while(!isEmpty) {
  17.             try {
  18.                 wait();//放弃锁,在这里等,本线程暂停
  19.             } catch (InterruptedException e) {
  20.                 e.printStackTrace();
  21.             }
  22.         }
  23.         //否则,执行下面代码
  24.         this.name = name+“–“+id++;
  25.         System.out.println(Thread.currentThread().getName()+” 生产者  “+this.name);
  26.         isEmpty = false;
  27.         this.notifyAll();//释放锁,所有 wait 中的线程重新唤醒,开始抢 cpu 执行权
  28.     }
  29.     public synchronized void get() { //消费
  30.         //如果是空的,就 wait()
  31.         while(isEmpty) {
  32.             try {
  33.                 wait();//放弃锁,在这里等,本线程暂停
  34.             } catch (InterruptedException e) {
  35.                 e.printStackTrace();
  36.             }
  37.         }
  38.         //否则,执行下面代码
  39.         System.out.println(Thread.currentThread().getName()+” 消费者  “+this.name);
  40.         isEmpty = true;
  41.         this.notifyAll();//释放锁,所有 wait 中的线程重新唤醒,开始抢 cpu 执行权
  42.     }
  43. }
  44. class Producer implements Runnable{
  45.     private Resource res;
  46.     public Producer(Resource res) {
  47.         this.res = res;
  48.     }
  49.     public void run() {
  50.         while(true) {
  51.             res.put(“化肥”);
  52.         }
  53.     }
  54. }
  55. class Consumer implements Runnable {
  56.     private Resource res;
  57.     public Consumer(Resource res) {
  58.         this.res = res;
  59.     }
  60.     public void run() {
  61.         while(true) {
  62.             res.get();
  63.         }
  64.     }
  65. }
  66. public class ProducerConsumerDemo {
  67.     public static void main(String[] args) {
  68.         Resource r = new Resource();
  69.         Producer producer = new Producer(r);
  70.         Consumer consumer = new Consumer(r);
  71.         Thread t1 = new Thread(producer);
  72.         Thread t2 = new Thread(producer);
  73.         Thread t3 = new Thread(consumer);
  74.         Thread t4 = new Thread(consumer);
  75.         t1.start();
  76.         t2.start();
  77.         t3.start();
  78.         t4.start();
  79.     }
  80. }

注意两点就可以:一个是判断仓库是否有货,用 while;另一个是,多线程用 notifyAll,不要用 notify


何处钟 , 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Java 线程生产者和消费者实例
喜欢 (0)
[15211539367@163.com]
分享 (0)

您必须 登录 才能发表评论!