java 线程同步问题之生产者消费者问题

public class ProducerAndConsumer {
 private static final int MAX_PRODUCE_COUNT = 10;

 /**
  *   */
 public static void main(String[] args) {
  TakeAndPut tp = new TakeAndPut();
  Producer p = new Producer(tp, MAX_PRODUCE_COUNT);
  Consumer c = new Consumer(tp, MAX_PRODUCE_COUNT);
  Thread p1 = new Thread(p);
  Thread c1 = new Thread(c);
  p1.start();
  c1.start();

 }

}

class TakeAndPut {
 private boolean Flag = false; // 判断产品是否生产好了

 public synchronized void put(int number) {
  System.out.println(" The Producer have done the " + number
    + " product ");
  while (Flag == true) { // 产品生产好了
   try {
    wait(); // 生产者等消费者消费
   } catch (InterruptedException e) {
    e.printStackTrace(); // 追踪异常事件发生时执行堆栈的内容
    System.out.println(e.toString()); // 打印输出异常的信息的简短描述
   }
  }
  Flag = true; // 设置生产好标志为true
  notifyAll(); // 通知消费者消费
 }

 public synchronized void take(int number) {
  while (Flag == false) { // 产品没生产好的情况下
   try {
    wait(); // 等待生产者生产
   } catch (InterruptedException e) {
    e.printStackTrace(); // 追踪异常事件发生时执行堆栈的内容
    System.out.println(e.toString()); // 打印输出异常的信息的简短描述
   }
  }
  System.out.println(" The Consumer can consume the " + number
    + " product");
  Flag = false; // 设置生产好的标志为false
  notifyAll(); // 通知生产者可以生产
 }
}

class Producer implements Runnable {// 生产者线程类
 TakeAndPut tp;
 int MAX_PRODUCE_COUNT; // 最大生产量

 public Producer(TakeAndPut tp, int max) {
  this.tp = tp;
  this.MAX_PRODUCE_COUNT = max;
 }

 public void run() {

  for (int i = 0; i < MAX_PRODUCE_COUNT; i++) {
   try {
    Thread.sleep((int) Math.random() * 2000); // 设定随机休眠时间
   } catch (InterruptedException e) {
    e.printStackTrace(); // 追踪异常事件发生时执行堆栈的内容
    System.out.println(e.toString()); // 打印输出异常的信息的简短描述
   }
   tp.put(i); // 调用put方法,执行线程之间的通信
  }

 }
}

class Consumer implements Runnable { // 消费者线程类
 TakeAndPut tp;
 int MAX_PRODUCE_COUNT; // 最大生产量

 public Consumer(TakeAndPut tp, int max) {
  this.tp = tp;
  this.MAX_PRODUCE_COUNT = max;
 }

 public void run() {
  for (int i = 0; i < MAX_PRODUCE_COUNT; i++) {
   try {
    Thread.sleep((int) Math.random() * 2000); // 设定随机休眠时间
   } catch (InterruptedException e) {
    e.printStackTrace(); // 追踪异常事件发生时执行堆栈的内容
    System.out.println(e.toString()); // 打印输出异常的信息的简短描述
   }
   tp.take(i); // 调用take方法,执行线程之间的通信
  }

 }

}
 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值