實現一個無限的工作隊列

來源:互聯網
上載者:User

 工作隊列是協調生產者與消費者之間的關係的,當隊列添加一個新的object時候,通知消費出來解決,直到empty,直到下一個訊息的到來。

 

public class WorkQueue {    LinkedList queue = new LinkedList();    // Add work to the work queue    public synchronized void addWork(Object o) {        queue.addLast(o);        notify();    }    // Retrieve work from the work queue; block if the queue is empty    public synchronized Object getWork() throws InterruptedException {        while (queue.isEmpty()) {            wait();        }        return queue.removeFirst();    }}

class Worker extends Thread {    // Special end-of-stream marker. If a worker retrieves    // an Integer that equals this marker, the worker will terminate.    static final Object NO_MORE_WORK = new Object();    WorkQueue q;    Worker(WorkQueue q) {        this.q = q;    }    public void run() {        try {            while (true) {                // Retrieve some work; block if the queue is empty                Object x = q.getWork();                // Terminate if the end-of-stream marker was retrieved                if (x == NO_MORE_WORK) {                    break;                }                // Compute the square of x                int y = ((Integer)x).intValue() * ((Integer)x).intValue();            }        } catch (InterruptedException e) {        }    }}

// Create the work queueWorkQueue queue = new WorkQueue();// Create a set of worker threadsfinal int numWorkers = 2;Worker[] workers = new Worker[numWorkers];for (int i=0; i<workers.length; i++) {    workers[i] = new Worker(queue);    workers[i].start();}// Add some work to the queue; block if the queue is full.// Note that null cannot be added to a blocking queue.for (int i=0; i<100; i++) {    queue.addWork(i);}// Add special end-of-stream markers to terminate the workersfor (int i=0; i<workers.length; i++) {    queue.addWork(Worker.NO_MORE_WORK);}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.