Java之线程通信(管程法)

生产者消费者问题(管程法)

线程通信最典型的一个应用场景就是生产者消费者问题。
这里我们用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();//唤醒所有线程
    }


}

执行结果如下:
在这里插入图片描述

如果对结果不是很明白的童鞋可以复制一下代码运行感受一下哈***************

*留赞再走哦~~~~*

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值