生产者消费者问题(管程法)
线程通信最典型的一个应用场景就是生产者消费者问题。
这里我们用java代码来模拟出生产者消费者之间的通信。
首先介绍一下管程法:
管程法在生产者消费者模式中,其实就是建立一个缓冲区,让生产者将生产产品(数据)放入缓冲区,而消费者从缓冲区获取产品。生产者和消费者之间不直接进行通信。
Java实现代码如下(代码均有详细注释,不过多赘述):
package com.zm.thread;
import static jdk.nashorn.internal.objects.NativeArray.push;
public class TestPC {
public static void main(String[] args) {
Store store=new Store(); //创建一个仓库对象
Productor productor = new Productor(store); //创建一个生产者对象并获取仓库对象
Consumer consumer = new Consumer(store); //创建一个消费者对象并获取仓库对象
new Thread(productor).start();//线程进入就绪状态
new Thread(consumer).start(); //线程就绪就绪状态
}
}
//生产者
class Productor implements Runnable{
Store store; //生产者需要获取仓库对象用以存储产品
Productor(Store store){
this.store=store;
}
@Override
public void run() {
for (int i = 1; i <= 100; i++) {
//将生产产品存入仓库
Product product=new Product(i);
store.push(product);
}
}
}
//消费者
class Consumer implements Runnable{
Store store;
Consumer(Store store){
this.store=store;
}
@Override
public void run() {
for (int i = 1; i <= 100; i++){
//取出一个产品
store.pop();
}
}
}
//产品
class Product{
//给产品一个id属性
int id;
public Product(int id){
this.id=id;
}
}
//仓库缓存区
class Store{
Product []products=new Product[10];//定义一个容纳10个产品的对象数组
static int count=0;//仓库产品数量计数,初始为0
public synchronized void push(Product product){
//判断仓库是否已满,若满则调用wait()方法令线程停止,使生产者停止产品的生产
if (count>=10)
{
try {
wait();//线程等待
} catch (InterruptedException e) {
e.printStackTrace();
}
}
products[count]=product;
count++;
System.out.println("生产者生产了第"+product.id+"个产品");
this.notifyAll();//唤醒所有线程
}
public synchronized void pop(){
//判断仓库是否存在产品,若无则调用wait()方法令线程停止,使消费者停止产品的获取
if (count==0){
try {
wait();//线程等待
} catch (InterruptedException e) {
e.printStackTrace();
}
}
count--;
Product product=products[count];
System.out.println("消费者消费了第"+product.id+"个产品");
this.notifyAll();//唤醒所有线程
}
}
执行结果如下:
如果对结果不是很明白的童鞋可以复制一下代码运行感受一下哈***************
*留赞再走哦~~~~*