日期:2014-05-20 浏览次数:20994 次
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){
}
}
r = (Runnable) queue.removeFirst(); // 取出该任务
}
// If we don't catch RuntimeException,
// the pool could leak threads
try {
r.run(); // 执行该任务
}
catch (RuntimeException e) {
// You might want to log something here
}
}
}
}
}