Java BlockingQueue methods

BlockingQueue方法有四種形式,其處理操作的方式不同,不能立即滿足,但可能在將來某個時候滿足:

第一種方法拋出異常

第二種方法返回特殊值(根據操作的不同,可以爲null或false)

第三種在操作成功之前無限期阻塞當前線程

第四種在放棄之前僅阻塞給定的最大時間限制,設置阻塞超時時間

下表總結了這些方法:

使用阻塞隊列實現多生產者-多消費者模型

class Producer implements Runnable {
    private final BlockingQueue queue;
    Producer(BlockingQueue q) { queue = q; }
    public void run() {
        try {
            while (true) { queue.put(produce()); }
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
    }
    Object produce() {
        System.out.println(Thread.currentThread().getName() + "線程生產");
        return "product";
    }
}

class Consumer implements Runnable {
    private final BlockingQueue queue;
    Consumer(BlockingQueue q) { queue = q; }
    public void run() {
        try {
            while (true) { consume(queue.take()); }
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
    }
    void consume(Object x) {
        System.out.println(Thread.currentThread().getName() + "線程消費:"+ x);
    }
}

class Setup {
    void main() {
        BlockingQueue q = new LinkedBlockingQueue(2);
        Producer p1 = new Producer(q);
        Producer p2 = new Producer(q);
        Consumer c1 = new Consumer(q);
        Consumer c2 = new Consumer(q);
        new Thread(p1).start();
        new Thread(p2).start();
        new Thread(c1).start();
        new Thread(c2).start();
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章