Java Blocking Queue

//Listing 8-1. The Blocking Queue Equivalent of Chapter 3’s PC Application
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class A
{
    public static void main(String[] args)
    {
        final BlockingQueue<Character> bq;
        bq = new ArrayBlockingQueue<Character>(26);
        final ExecutorService executor = Executors.newFixedThreadPool(2);
        Runnable producer = () ->
        {
            for (char ch = 'A'; ch <= 'Z'; ch++)
            {
                try
                {
                    bq.put(ch);
                    System.out.printf("%c produced by " + "producer.%n", ch);
                }
                catch (InterruptedException ie)
                {
                }
            }
        };        
        executor.execute(producer);
        
        Runnable consumer = () ->
        {
            char ch = '\0';
            do
            {
                try
                {
                    ch = bq.take();
                    System.out.printf("%c consumed by " + "consumer.%n", ch);
                }
                catch (InterruptedException ie)
                {
                }
            }
            while (ch != 'Z');
            executor.shutdownNow();
        };
        executor.execute(consumer);
    }    
}

 

    原文作者:java 线程池
    原文地址: http://www.cnblogs.com/rojas/p/5382598.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞