package ThreadDemo;
// 生产者消费者问题:利用缓冲区:管程法
// wait()令自己等待 ,notify()唤醒别的线程
public class Test25_Producer_Consumer_1 {
public static void main(String[] args) {
SynBuffer synBuffer = new SynBuffer();
new Consumer(synBuffer).start();
new Producer(synBuffer).start();
}
}
//生产者
class Producer extends Thread{
SynBuffer synBuffer= new SynBuffer();
public Producer(SynBuffer synBuffer) {
this.synBuffer = synBuffer;
}
@Override
public void run() {
for (int i = 1; i <=100; i++) {
try {
synBuffer.push();
System.out.println("生产了第"+i+"件产品");
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
//消费者
class Consumer extends Thread{
SynBuffer synBuffer= new SynBuffer();
public Consumer(SynBuffer synBuffer) {
this.synBuffer = synBuffer;
}
@Override
public void run() {
for (int i = 1; i <=100; i++) {
try {
synBuffer.pop();
System.out.println("消费了第"+i+"件产品");
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
// 产品
class Product {
int id;
public Product(int id){
this.id=id;
}
}
// 安全的缓冲区
class SynBuffer{
Product[] products=new Product[10]; //缓冲区大小
static int count=0; // 产品计数,一开始为零,需要生产
// 生产者
public synchronized void push() throws InterruptedException {
// 判定能否生产,满了的话,等待消费者消费
if (count>=10){
System.out.println("缓冲区满了,需要消费者及时消费");
wait();
}
// 不满的话,继续生产
count++;
// 有储存就通知消费者消费
this.notify();
}
// 消费者
public synchronized void pop() throws InterruptedException {
// 判定能否消费,没有储存就等待生产者生产
if (count<=0){
System.out.println("没有产品可以消费了,需要生产者生产");
wait();
}
// 有的话就消费
count--;
// 消费之后,再次通知生产者生产
this.notify();
}
// 这里应该是让chickens[count]=null吧
}
标签:25,SynBuffer,Producer,管程,缓冲区,new,public,synBuffer
From: https://www.cnblogs.com/zhanjianhai/p/17688029.html