实现一个无限的工作队列

 工作队列是协调生产者与消费者之间的关系的,当队列添加一个新的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 queue
WorkQueue queue = new WorkQueue();

// Create a set of worker threads
final 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 workers
for (int i=0; i<workers.length; i++) {
    queue.addWork(Worker.NO_MORE_WORK);
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值