多线程协作--生产者消费者问题


//管程法:生产者消费者问题(线程协作)
public class Exercise {
public static void main(String[] args) {
//建立缓冲区对象 作为容器
Buffer container=new Buffer();
new Producer(container).start();//启动生产者线程
new Consumers(container).start();//启动消费者线程
}
}
//生产者
class Producer extends Thread{
//通过缓存区建立容器
Buffer buffer;
//构造器
public Producer(Buffer buffer) {
this.buffer = buffer;
}
//重写run方法
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("生产了"+i+"个产品");
buffer.Push(new Product(i));//栈入
}
}
}
//消费者
class Consumers extends Thread{
//通过缓存区建立容器
Buffer buffer;
//构造器
public Consumers(Buffer buffer) {
this.buffer = buffer;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("消费了"+buffer.Pop().id+"个产品");//栈出
}
}
}
//产品
class Product extends Thread{
//产品编号
int id;
public Product(int id) {
this.id = id;
}
}
//缓冲区 负责建立容器
class Buffer{
Product []products=new Product[10];//根据产品来建立容器
int count=0;//计数器
public synchronized void Push(Product product)//生产者入栈
{
//判断容器是否满
//如果容器满了,那么就等待消费者消费
if (count==products.length)
{
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果没满,就丢入产品,再通知生产者生产
products[count]=product;
count++;
this.notifyAll();//唤醒多个线程
}
//消费者出栈
public synchronized Product Pop(){
//判断是否可以消费
//如果容器内为空,则需要等待生产者生产
if (count==0)
{
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果容器内有产品,那么就可以消费
//把容器内的产品,放入到产品的临时变量里,随拿随取
count--;
Product product=products[count];
//消费完之后,通知生产者去生产
this.notifyAll();
return product;
}
}