java併發-BlockingQueue

weixin_33843409發表於2018-04-20

java.util.concurrent.BlockingQueue 介面有以下阻塞佇列的實現

  • ArrayBlockingQueue:規定大小的BlockingQueue,其建構函式必須帶一個int引數來指明其大小.其所含的物件是以FIFO(先入先出)順序排序的.
  • LinkedBlockingQueue:大小不定的BlockingQueue,若其建構函式帶一個規定大小的引數,生成的BlockingQueue有大小限制,若不帶大小引數,所生成的BlockingQueue的大小由Integer.MAX_VALUE來決定.其所含的物件是以FIFO(先入先出)順序排序的
  • PriorityBlockingQueue:類似於LinkedBlockQueue,但其所含物件的排序不是FIFO,而是依據物件的自然排序順序或者是建構函式的Comparator決定的順序.
  • SynchronousQueue:特殊的BlockingQueue,對其的操作必須是放和取交替完成的.

FIFO 佇列 :LinkedBlockingQueue、ArrayListBlockingQueue(固定長度)
優先順序佇列 :PriorityBlockingQueue

提供了阻塞的 take() 和 put() 方法:如果佇列為空 take() 將阻塞,直到佇列中有內容;如果佇列為滿 put() 將阻塞,指到佇列有空閒位置。

package com.br.lucky.utils;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * @author 10400
 * @create 2018-04-20 1:52
 */
public class BlockingQueueDemo {

    private static BlockingQueue<String> queue = new ArrayBlockingQueue<>(5);

    private static class Producer extends Thread {
        @Override
        public void run() {
            try {
                Thread.sleep(5000);
                double random = Math.random();
                queue.put(""+random);
                System.out.println("produce :" + random);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private static class Consumer extends Thread {

        @Override
        public void run() {
            try {
                Thread.sleep(3000);
                String product = queue.take();
                System.out.println("consume :"+product);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        for (int i = 0; i < 2; i++) {
            Producer producer = new Producer();
            producer.start();
        }
        for (int i = 0; i < 5; i++) {
            Consumer consumer = new Consumer();
            consumer.start();
        }
        for (int i = 0; i < 3; i++) {
            Producer producer = new Producer();
            producer.start();
        }
    }
}

相關文章