生产者与消费者模式

生产者消费者模式是一个十分经典的多线程协作的模式,弄懂生产者消费者问题能够让我们对多线程编程的理解更加深刻。

// Main.java
        Box b = new Box();
        Producer p = new Producer(b);   // 生产者
        Customer c = new Customer(b);   // 消费者

        Thread th1 = new Thread(p);
        Thread th2 = new Thread(c);

        th1.start();
        th2.start();
// Producer.java
public class Producer implements Runnable{
    private Box b;
    public Producer(Box b){
        this.b = b;
    }

    @Override
    public void run() {
        for(int i = 0; i < 30;i++){
            b.put(i);
        }
    }
}
// Customer.java
public class Customer implements Runnable{
    private Box b;
    public Customer(Box b){
        this.b = b;
    }

    @Override
    public void run() {
        while(true){
            b.get();
        }
    }
}
// Box.java
public class Box {
    private int milk;
    private boolean state = false;  // 有无奶的状态
    //    producer 在跑这个线程
    public synchronized void put(int milk){
        if(state){          // 有奶 就进行等待,等消费者消费
            try{
                wait();
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }

        this.milk = milk;
        System.out.println("送奶工将第" + this.milk + "瓶奶放入奶箱");
        state = true;
//        notifyAll();
    }
    //    Customer 在跑这个线程
    public synchronized void get(){
        if(!state){         // 无奶 就进行等待,等生产者生产
            try{
                wait();
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }
        System.out.println("用户拿到第" + this.milk + "瓶奶");
        state = false;
//        notifyAll();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值