生产者与消费者模式之工作队列原生的工作队列与线程池,讲解生产者与消费者模式写道package referenceimpo
生产者与消费者模式之工作队列
原生的工作队列与线程池,讲解生产者与消费者模式写道package reference;
import java.util.LinkedList;
@SuppressWarnings("all")
public class WorkQueue {
private final int nThreads;
private final PoolWorker[] threads;
private final LinkedList queue;
public WorkQueue(int nThreads)
{
this.nThreads = nThreads;
queue = new LinkedList();
threads = new PoolWorker[nThreads];
for (int i=0; i<nThreads; i++) {
threads[i] = new PoolWorker();
threads[i].start();
}
}
public void execute(Runnable r) {
synchronized(queue) {
queue.addLast(r);
queue.notify();
}
}
private class PoolWorker extends Thread {
public void run() {
Runnable r;
while (true) {
synchronized(queue) {
while (queue.isEmpty()) {
try
{
queue.wait();
}
catch (InterruptedException ignored)
{
//如何处理阻塞异常,我建议捕捉或者抛出给调用者,禁止生吞
//比如
Thread.interrupted();
}
}
r = (Runnable) queue.removeFirst();
}
try {
r.run();
}
catch (RuntimeException e) {
// If we don't catch RuntimeException,
// the pool could leak threads
// You might want to log something here
}
}
}
}
}
?