Java多线程之线程通信

本篇学习的是线程通信的管程法,设置缓冲区,以生产者和消费者 为场景。

package lesson04;

/**
 * 生产者消费者模型:利用缓冲区---->管程法
 */
public class TestCP {
    public static void main(String[] args) {
        SyContiner continer = new SyContiner();
        Productor productor = new Productor(continer);
        Customer customer = new Customer(continer);
        productor.start();
        customer.start();

    }
}


//生产者
class Productor extends Thread {
    SyContiner continer;
    public Productor(SyContiner continer) {
        this.continer = continer;
    }
    @Override
    public void run() {
        //生产产品
        for (int i = 0; i < 100; i++) {
            continer.push(new Chicken(i));
            System.out.println("生产了"+i+"只鸡");
        }
    }
}
//消费者
class Customer extends Thread {
    SyContiner continer;
    public Customer(SyContiner continer) {
        this.continer = continer;
    }
    //消费产品
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            try {
                System.out.println("消费了"+continer.pop().id+"只鸡");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

//产品
class Chicken {
    int id ;

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

//缓冲器:容器
class SyContiner {
    //设置容器大小
    Chicken[] chickens = new Chicken[10];
    int count = 0;

    //需要生产者放入产品
    public synchronized void push (Chicken chicken) {
        //如果容器满了,就需要等待消费者消费
        if (count == chickens.length) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //如果没有满,就放入产品
        chickens[count] = chicken;
        count++;
        //通知消费者进行消费
        this.notify();
    }
    //消费者消费产品
    public synchronized Chicken pop () throws InterruptedException {
        if (count == 0) {
            //等待生产者生产
            this.wait();
        }
        //如果可以消费
        count--;
        Chicken chicken = chickens[count];
        //吃完通知生产者生产
        this.notify();
        return chicken;
    }

}


 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值