BlockingQueue 解决生产者消费者问题

BlockingQueue 是线程安全的,并且在调用 put,take 方法时会阻塞线程。

基于以上特性,可以不加任何锁解决生产者消费者问题。

public static void main(String[] args) throws InterruptedException {
        BlockingQueue<String> bq = new LinkedBlockingQueue<>(2);

        CountDownLatch cdl = new CountDownLatch(2);

        Thread t1 = new Thread(()->{ // 生产者线程
                try {
                    for (int i = 0; i < 100; i++)
                        bq.put("z" + i);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    cdl.countDown();
                }
        });

        Thread t2 = new Thread(()->{ // 消费者线程
                try {
                    for (int i = 0; i < 100; i++)
                        System.out.println(bq.take());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    cdl.countDown();
                }
        });
        t2.start();
        t1.start();
        cdl.await(); // 等待两个线程结束
        System.out.println(bq.size());

    }
发布了16 篇原创文章 · 获赞 3 · 访问量 4528

猜你喜欢

转载自blog.csdn.net/qq_29697901/article/details/90405141