Java 多线程 生产者—消费者 通用模式(synchronized已被Lock替代!)

生产者-消费者模式详解
本文详细介绍了经典的生产者-消费者模式实现方式,利用Java语言中的synchronized关键字和wait/notifyAll方法,确保多线程环境下资源的正确生产和消费。通过具体代码示例展示了如何在多个生产者和消费者之间协调工作。
 //生产者——消费者 通用模式
// 1、while()
// 2、notifyAll()
//理解思路:
// 1、标记flag,理解为仓库里有产品。则不再生产改变标记,在不再生产前唤醒消费线程们。
// 2、生产的线程则因为循环,执行等待。
// 3、等待的线程被唤醒后,第一件事是重新判断标记,是否仓库有货,即while循环的条件判断,如没货才可以生产,有货则消费。
class Resource {
 private String name;
 private int count = 0;
 private boolean flag = false;
 public synchronized void produce(String name) {
  while (flag) {
   try {
    wait();
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
  }
  this.name = name + (++count);
  System.out.println("生产:" + this.name);
  flag = !flag;
  notifyAll();
 }
 public synchronized void consume() {
  while (!flag) {
   try {
    wait();
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
  }
  System.out.println("...........消费:" + name);
  flag = !flag;
  notifyAll();
 }
}
class Producer implements Runnable {
 private Resource r;
 public Producer(Resource r) {
  this.r = r;
 }
 public void run() {
  while (true) {
   r.produce("商品");
  }
 }
}
class Consumer implements Runnable {
 private Resource r;
 public Consumer(Resource r) {
  this.r = r;
 }
 public void run() {
  while (true) {
   r.consume();
  }
 }
}
public class ProducerConsumerDemo {
 public static void main(String[] args) {
  Resource r = new Resource();
  Producer pro = new Producer(r);
  Consumer con = new Consumer(r);
  
  
  //多个生产者消费者时:
  new Thread(pro).start();
  new Thread(pro).start();
  new Thread(con).start();
  new Thread(con).start();
 }
}

转载于:https://my.oschina.net/cuncaojin/blog/369467

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值