多线程-管程法解决线程间通信问题

管程法

并发协作模型“生产者/消费者模式”---->管程法

  • 生产者:负责生产数据的模块(可能是方法,对象,线程,进程);
  • 消费者:负责处理数据的模块(可能是方法,对象,线程,进程);
  • 缓冲区:消费者不能直接使用生产者的数据,他们之间有“缓冲区”.

生产者将生产好的数据放入缓冲区,消费者从缓冲区拿出数据两个线程共用一个缓冲区对象.
在这里插入图片描述

//生产者与 消费者 鸡肉:wait()以及notifyAll(),定义一个缓冲区:管程法
public class TestPC {
    public static void main(String[] args) {
        SynContainer container=new SynContainer();
        new Producter(container).start();
        new Customer(container).start();
    }

}
class Producter extends Thread{
    SynContainer container;
    public Producter(SynContainer container){
        this.container=container;
    }
    public void run(){
        for (int i = 1; i <100; i++) {
            try {
                this.container.push(new Chiken(i)); //给每只鸡设置编号
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("生产了第" + i+"只鸡");
        }
    }
}
class Customer extends Thread {
    SynContainer container;

    public Customer(SynContainer container) {
        this.container = container;
    }

    @Override
    public void run() {
        for (int i = 1; i < 100; i++) {
            try {

                System.out.println("消费了第" + this.container.pop().id+"只鸡");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
    //产品
    class Chiken {
        int id;

        public Chiken(int id) {
            this.id = id;
        }
    }

    class SynContainer {
        //定义一个缓冲区
        int count = 0;
        Chiken chikens[] = new Chiken[10]; //chikens数组

        public synchronized void push(Chiken chiken) throws InterruptedException { //生产 者
            if (count == chikens.length) {
                //当缓冲区鸡的数量满了之后,生产者等待,消费者进入
                this.wait();
            }
            chikens[count] = chiken;
            count++;
            //可以通知消费者消费
            this.notifyAll();
        }

        public synchronized Chiken pop() throws InterruptedException {  //消费者消费
            if (count == 0) {
                //提醒消费者等待,生产者进入
                this.wait();
            }
            Chiken chiken = chikens[count-1];//这里是count-1,要避免数组越界
            count--;
            this.notifyAll();  //通知生产值生产
            return chiken;    //返回,让消费者消费
        }
    }

运行结果:
在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值