1. 程式人生 > >Java之三大集合

Java之三大集合

/**
 * 多執行緒模擬實現生產者/消費者模型
 */
public class BlockingQueueTest{
    /**
     * 
     * 定義裝蘋果的籃子
     * 
     */
    public class Basket {
        // 籃子,能夠容納3個蘋果
        BlockingQueue basket = new LinkedBlockingQueue(3);

        // 生產蘋果,放入籃子
        public void produce() throws InterruptedException {
            // put方法放入一個蘋果,若basket滿了,等到basket有位置
            basket.put("An apple");
        }

        // 消費蘋果,從籃子中取走
        public String consume() throws InterruptedException {
            // take方法取出一個蘋果,若basket為空,等到basket有蘋果為止(獲取並移除此佇列的頭部)
            return basket.take();
        }
    }

    // 定義蘋果生產者
    class Producer implements Runnable {
        private String instance;
        private Basket basket;

        public Producer(String instance, Basket basket) {
            this.instance = instance;
            this.basket = basket;
        }

        public void run() {
            try {
                while (true) {
                    // 生產蘋果
                    System.out.println("生產者準備生產蘋果:" + instance);
                    basket.produce();
                    System.out.println("!生產者生產蘋果完畢:" + instance);
                    // 休眠300ms
                    Thread.sleep(300);
                }
            } catch (InterruptedException ex) {
                System.out.println("Producer Interrupted");
            }
        }
    }

    // 定義蘋果消費者
    class Consumer implements Runnable {
        private String instance;
        private Basket basket;

        public Consumer(String instance, Basket basket) {
            this.instance = instance;
            this.basket = basket;
        }

        public void run() {
            try {
                while (true) {
                    // 消費蘋果
                    System.out.println("消費者準備消費蘋果:" + instance);
                    System.out.println(basket.consume());
                    System.out.println("!消費者消費蘋果完畢:" + instance);
                    // 休眠1000ms
                    Thread.sleep(1000);
                }
            } catch (InterruptedException ex) {
                System.out.println("Consumer Interrupted");
            }
        }
    }

    public static void main(String[] args) {
        BlockingQueueTest test = new BlockingQueueTest();

        // 建立一個裝蘋果的籃子
        Basket basket = test.new Basket();

        ExecutorService service = Executors.newCachedThreadPool();
        Producer producer = test.new Producer("生產者001", basket);
        Producer producer2 = test.new Producer("生產者002", basket);
        Consumer consumer = test.new Consumer("消費者001", basket);
        service.submit(producer);
        service.submit(producer2);
        service.submit(consumer);

    }

}