首页 > 其他 > 详细

经典笔试题:基于阻塞队列实现的简单生产者消费者模式

时间:2020-05-24 22:25:31      阅读:72      评论:0      收藏:0      [点我收藏+]

基于阻塞队列实现的简单生产者消费者模式,代码如下:

public class BlockingQueue_Test {
    private static final int MAX_CAPACITY = 10;
    private static ArrayBlockingQueue<Object> goods = new ArrayBlockingQueue<Object>(MAX_CAPACITY);

    public static void main(String[] args) {
        (new ProducerThread()).start();
        (new ConsumerThread()).start();
    }

    static class ProducerThread extends Thread {
        public void run() {
            while (true) {
                // 每隔 1000 毫秒生产一个商品
                try {
                    Thread.sleep(1000);

                    goods.put(new Object());
                    System.out.println("Produce goods, total: " + goods.size());
                } catch (InterruptedException e) {
                }
            }
        }
    }

    static class ConsumerThread extends Thread {
        public void run() {
            while (true) {
                // 每隔 5000 毫秒消费一个商品
                try {
                    Thread.sleep(5000);

                    goods.take();
                    System.out.println("Consume goods, total: " + goods.size());
                } catch (InterruptedException e) {
                }
            }
        }
    }
}

运行结果如下:

Produce goods, total: 1
Produce goods, total: 2
Produce goods, total: 3
Produce goods, total: 4
Consume goods, total: 3
Produce goods, total: 4
Produce goods, total: 5
Produce goods, total: 6
Produce goods, total: 7
Produce goods, total: 8
Consume goods, total: 7
Produce goods, total: 8
Produce goods, total: 9
Produce goods, total: 10
Consume goods, total: 9
Produce goods, total: 10
Consume goods, total: 9
Produce goods, total: 10

经典笔试题:基于阻塞队列实现的简单生产者消费者模式

原文:https://www.cnblogs.com/gaopengpy/p/12952910.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!