public class ThreadPool {
private BlockingQueue taskQueue = null;
private List<PoolThread> threads = new ArrayList<PoolThread>();
private boolean isStopped = false;
public ThreadPool(int noOfThreads, int maxNoOfTasks) {
taskQueue = new BlockingQueue(maxNoOfTasks);
for (int i=0; i<noOfThreads; i++) {
threads.add(new PoolThread(taskQueue));
}
for (PoolThread thread : threads) {
thread.start();
}
}
public void synchronized execute(Runnable task) {
if(this.isStopped) throw
new IllegalStateException("ThreadPool is stopped");
this.taskQueue.enqueue(task);
}
public synchronized boolean stop() {
this.isStopped = true;
for (PoolThread thread : threads) {
thread.stop();
}
}
}
<span style="color: rgb(102, 102, 102); font-family: Arial, Helvetica, sans-serif; line-height: 35px; widows: auto; background-color: rgb(255, 255, 255);">(校注:原文有编译错误,我修改了下)</span>
原文地址:http://blog.csdn.net/sunlei1980/article/details/46484189