Java 生產者消費者實現 —— BlockingQueue

前言

對著《Java 編程思想》,通過wait - notifyAll實現了生產者消費者模式。今天用BlockingQueue實現一下。

BlockingQueue

簡單實現

生產者和消費者,共用一個BlockingQueue。為什么BlockingQueue能夠實現生產者-消費者模型呢?對于puttake兩個操作,注釋如下:

/**
 * Inserts the specified element into this queue, waiting if necessary
 * for space to become available.
 *
 * @param e the element to add
 * @throws InterruptedException if interrupted while waiting
 * @throws ClassCastException if the class of the specified element
 *         prevents it from being added to this queue
 * @throws NullPointerException if the specified element is null
 * @throws IllegalArgumentException if some property of the specified
 *         element prevents it from being added to this queue
 */
void put(E e) throws InterruptedException;
/**
 * Retrieves and removes the head of this queue, waiting if necessary
 * until an element becomes available.
 *
 * @return the head of this queue
 * @throws InterruptedException if interrupted while waiting
 */
E take() throws InterruptedException;

Apple.java,生產和消費的對象。

public class Apple {
    
    private int id;
    
    public Apple(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    @Override
    public String toString() {
        return "Apple [id=" + id + "]";
    }
}

生產者:

public class Producer {
    BlockingQueue<Apple> queue;
    
    public Producer(BlockingQueue<Apple> queue) {
        this.queue = queue;
    }
    
    public boolean put(Apple apple) {
        return queue.offer(apple);
    }
}

消費者:

public class Consumer {
    BlockingQueue<Apple> queue;
    
    public Consumer(BlockingQueue<Apple> queue) {
        this.queue = queue;
    }
    
    public Apple take() throws InterruptedException {
        return queue.take();
    }
}

測試:

public class TestConsumer {
    
    public static void main(String[] args) {

        final BlockingQueue<Apple> queue = new LinkedBlockingDeque<Apple>(100);
        
        // 生產者
        new Thread(new Runnable() {
            
            int appleId = 0;
            Producer producer = new Producer(queue);
            
            @Override
            public void run() {
                try {
                    while (true) {
                        TimeUnit.SECONDS.sleep(1);
                        producer.put(new Apple(appleId++)); 
                        producer.put(new Apple(appleId++)); 
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

        // 消費者
        new Thread(new Runnable() {
            Consumer consumer = new Consumer(queue);
            
            @Override
            public void run() {
                try {
                    while (true) {
                        System.out.println(consumer.take().getId());
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}

輸出:

生產者生產2個Apple,消費者立即消費掉。

改進

上述代碼存在一些問題:

  • 生產者和消費者,都僅用于特定的類型Apple
  • 在使用過程中,需要自己定義BlockingQueue,自行實現生產者和消費者的線程,使用復雜
  • 如果要定義多個消費者線程,需要多次手動編寫代碼
  • 生產者并沒有專注自身的功能:存儲要消費的對象
  • 消費者并沒有專注自身的功能:取出對象、如何消費對象

改進后的代碼如下:

Apple類未更改。

Producer變為抽象類,并使用泛型。里面新增線程池,用于運行消費者線程。

public abstract class Producer<E> {
    protected BlockingQueue<E> queue;
    protected ExecutorService threadPool = Executors.newCachedThreadPool();
    public static final int DEFAULT_QUEUE_LENGTH = 10000;
    
    public Producer(int capacity) {
        initQueue(capacity);
    }
    
    public BlockingQueue<E> getQueue() {
        return queue;
    }

    public void setQueue(BlockingQueue<E> queue) {
        this.queue = queue;
    }

    public boolean put(E apple) {
        return queue.offer(apple);
    }
    
    private void initQueue(int capacity) {
        if (queue == null) {
            synchronized (this) {
                if (queue == null) {
                    queue = new LinkedBlockingDeque<E>(capacity < 0 ? DEFAULT_QUEUE_LENGTH : capacity);
                }
            }
        }
    }
    
    protected void consumerThread(int consumerCount, Consumer<E> consumer) {
        for (int i = 0; i < consumerCount; i++) {
            threadPool.execute(consumer);
        }
    }
}

Consumer也變成抽象類,使用泛型,并實現了Runnable接口。其中run方法的實現邏輯是:從阻塞隊列中取出一個對象,并調用抽象方法consume。該方法是具體的消費者實現的消費邏輯。

public abstract class Consumer<E> implements Runnable{
    BlockingQueue<E> queue;
    
    /**
     * 數據逐個處理
     * @param data
     */
    protected abstract void consume(E data);
    
    @Override
    public void run() {
        while (true) {
            try {
                E data = take();
                try {
                    consume(data);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    
    public Consumer(BlockingQueue<E> queue) {
        this.queue = queue;
    }
    
    public E take() throws InterruptedException {
        return queue.take();
    }
}

AppleProducer:Apple的生產者,使用非延遲加載的單例模式,指定阻塞隊列的長度、消費者線程數量。

public class AppleProducer extends Producer<Apple>{
    
    // 并沒有延遲加載
    public static AppleProducer INSTANCE = new AppleProducer(DEFAULT_QUEUE_LENGTH, 1); 

    private AppleProducer(int capacity, int consumerCount) {
        super(capacity);
        AppleConsumer consumer = new AppleConsumer(queue);
        consumerThread(consumerCount, consumer);
    }
}

AppleConsumer:Apple的消費者,要實現具體的消費方法consume。這里只是在控制臺輸出對象信息。

public class AppleConsumer extends Consumer<Apple>{

    public AppleConsumer(BlockingQueue<Apple> queue) {
        super(queue);
    }

    @Override
    protected void consume(Apple data) {
        System.out.println(data);
    }
}

測試:這里只需要獲取AppleProducer,調用put方法添加對象即可!在隊列中有對象Apple時,會有線程取出Apple,自動調用AppleConsumer的consume方法。

public class TestConsumer {
    
    public static void main(String[] args) throws InterruptedException {

        AppleProducer producer = AppleProducer.INSTANCE;
        for (int i = 0; i < 60; i++) {
            producer.put(new Apple(i));
        }
    }
}

有待改進的地方

  • 并沒有面向接口編程,仍然是通過繼承來實現的,代碼有耦合(但是也不能算是缺點吧)
  • 阻塞隊列直接使用LinkedBlockingDeque,并不夠靈活(PriorityBlockingQueue等)
  • 對于線程,并沒有好的名字,調試等并不直觀
  • 如果有多個生產者-消費者,例如增加了Banana,管理仍然不夠直觀。可以增加一個方法,能夠打印出所有的生產者-消費者
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,825評論 6 546
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,814評論 3 429
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,980評論 0 384
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 64,064評論 1 319
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,779評論 6 414
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 56,109評論 1 330
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 44,099評論 3 450
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 43,287評論 0 291
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,799評論 1 338
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,515評論 3 361
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,750評論 1 375
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,221評論 5 365
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,933評論 3 351
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,327評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,667評論 1 296
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,492評論 3 400
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,703評論 2 380

推薦閱讀更多精彩內容

  • 考查Java的并發編程時,手寫“生產者-消費者模型”是一個經典問題。有如下幾個考點: 對Java并發模型的理解 對...
    猴子007閱讀 4,417評論 12 33
  • 相關概念 面向對象的三個特征 封裝,繼承,多態.這個應該是人人皆知.有時候也會加上抽象. 多態的好處 允許不同類對...
    東經315度閱讀 1,976評論 0 8
  • 一、多線程 說明下線程的狀態 java中的線程一共有 5 種狀態。 NEW:這種情況指的是,通過 New 關鍵字創...
    Java旅行者閱讀 4,721評論 0 44
  • 東野圭吾的作品作為懸疑推理小說的先鋒,讀的多了,就很容易被貼標簽,滿滿都是充滿理性燒腦的情節。天天腦袋處于放空的自...
    我冰叔閱讀 693評論 0 0
  • 《朗讀者》里對汪明荃和羅家英訪談的那一期給人留下很深的印象。 汪姐說:他們到六十歲這個年紀才選擇結婚,是很重視這一...
    大頭諾阿諾閱讀 851評論 0 0