生産者と消費者へのBlockingQueueの決意

BlockingQueueのは、スレッドセーフである、とコールプット、スレッドが方法を取るブロックします。

上記の特性に基づいて、任意のロックの生産者と消費者なしで解決することができます。

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