生产者和消费者

                                                     生产者和消费者

 java 1.5以后用
1. lock.lock()
      同步代码
     lock.unlock()
替代了synchronized同步代码块
2.condition.await()替代了wait();
3.condition.signal替代了notify
4.condition.signalAll()替代了notifyAll

public class ProducersAndConsumer {

 /**
  * @param args
  */
 public static void main(String[] args) {
  Resource re = new Resource(1);
  new Thread(new Producer(re)).start();//t1
  new Thread(new Producer(re)).start();//t2
  new Thread(new Consumer(re)).start();//t3
  new Thread(new Consumer(re)).start();//t4

 }

}

class Resource {
 private String name;
 private int count;
 boolean flag;

 public Resource(int count) {
  this.count = count;
 }

 /*
  * t1等待 t2在等待 t3没启动 t4没启动
  * t3启动 t1唤醒 t2在等待 t4没启动
  * t3等待 t1唤醒 t2在等待 t4等待
  * t1启动 t2被唤醒 t3在等待 t4等待
  *  此时t2不会判断标志位就往下执行了,导致生产了多次,只消费了1次的情况

  * 所以我加了一个while循环来防止这种问题的发生

  */
 private Lock lock = new ReentrantLock();
 private Condition condition = lock.newCondition();

 public void set(String name) {
  lock.lock();
  try {
   while (flag) {
      condition.await();  // java1.5以前的写法this.wait();
   }
   this.name = name + "---" + count++;
   flag = true;
   System.out.println(Thread.currentThread().getName()
     + ".....生产了ipnone" + count);
        condition.signalAll(); //java1.5以前的写法: this.notifyAll();
  } catch (InterruptedException e) {
   e.printStackTrace();
  } finally {
   lock.unlock();
  }
 }

 public void out() {
  lock.lock();
  try {
   while (!flag) {
    condition.await();// java1.5以前的写法 this.wait();
   }
   System.out.println(Thread.currentThread().getName()
     + "----消费了iphone" + count);
   condition.signalAll();// java1.5以前的写法 this.notifyAll();
   flag = false;
  } catch (InterruptedException e) {
   e.printStackTrace();
  }finally{
   lock.unlock();
  }
 }
}

class Producer implements Runnable {
 private Resource res;

 public Producer(Resource res) {
  this.res = res;
 }

 @Override
 public void run() {
  while (true) {
   res.set("iphone");
  }
 }

}

class Consumer implements Runnable {
 private Resource res;

 public Consumer(Resource res) {
  this.res = res;
 }

 @Override
 public void run() {
  while (true) {
   res.out();
  }
 }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值