`
xylong
  • 浏览: 188224 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

生产者与消费者模式之工作队列

阅读更多

原生的工作队列与线程池,讲解生产者与消费者模式
写道
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
}
}
}
}

}
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics