BlockingQueue resolve to producers and consumers

BlockingQueue is thread-safe, and the call put, will block threads take method.

Based on the above characteristics, can be solved without any lock producers and consumers.

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());

    }

 

Published 16 original articles · won praise 3 · Views 4528

Guess you like

Origin blog.csdn.net/qq_29697901/article/details/90405141