Java多线程之线程间通信--生产者/消费者模式

  等待(wait)/通知(notify)模式最经典的案例就是“生产者/消费者”模式。虽然此模式在使用上有几种“变形”,还有一些小的注意事项,但原理都是基于wait/notify的。

public class Storage {
    //仓库最大存储量
    private final int MAX_SIZE = 10;
    // 仓库存储的载体
    private LinkedList<Object> list = new LinkedList<Object>();

    // 生产num个产品
    public void produce() {
        // 同步代码段
        synchronized (list) {
            // 如果仓库剩余容量不足
            while (list.size()  ==  MAX_SIZE) {
                System.out.println("【库存量】:" + list.size() + "已经达到最大,暂时不能执行生产任务!");
                try {
                    list.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            list.add(new Object());

            System.out.println( "生产一个产品,/t【现仓储量为】:" + list.size());

            list.notifyAll();
        }
    }

    // 消费num个产品
    public void consume() {
        // 同步代码段
        synchronized (list) {
            // 如果仓库存储量不足
            while (list.size() == 0) {
                System.out.println("/t【库存量】:" + list.size() + ",暂时不能执行消费任务!");

                try {
                    // 由于条件不满足,消费阻塞
                    list.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            list.remove();
            System.out.println( "消费一个产品,/t【现仓储量为】:" + list.size());

            list.notifyAll();
        }
    }

}
public class Producer extends Thread {
    private Storage storage;

    // 构造函数,设置仓库
    public Producer(Storage storage) {
        this.storage = storage;
    }

    public void run() {
        for(int i = 0; i < 100; i++) {
            storage.produce();
        }
    }

}
public class Consumer extends Thread {
    private Storage storage;

    // 构造函数,设置仓库
    public Consumer(Storage storage) {
        this.storage = storage;
    }

    public void run() {
        for(int i = 0; i < 100; i++) {
            storage.consume();
        }
    }
}
public class Test {
    public static void main(String[] args) {
        Storage storage = new Storage();

        Producer producer = new Producer(storage);
        producer.start();

        Consumer consumer = new Consumer(storage);
        consumer.start();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值