public class DefaultThreadPool implements ThreadPool{//线程池最大限制数
private static final int MAX_WORKER_NUMBERS = 10;//线程池默认的数量
private static final int DEFAULT_WORKER_NUMBERS= 5;//线程池最小数量
private static final int MIN_WORKER_NUMBERS = 1;//这是一个任务列表,将会向里面插入任务
private final LinkedList jobs = new LinkedList() ;//工作者列表
private final List workers = Collections.synchronizedList(new ArrayList()) ;//工作者线程的数量
private int workerNum =DEFAULT_WORKER_NUMBERS ;//线程编号生成
private AtomicLong threadNum = newAtomicLong() ;publicDefaultThreadPool(){
initializeWorkers(DEFAULT_WORKER_NUMBERS);
}public DefaultThreadPool(intinitSize){
workerNum= initSize > MAX_WORKER_NUMBERS ?MAX_WORKER_NUMBERS :
initSize< MIN_WORKER_NUMBERS ?MIN_WORKER_NUMBERS : initSize ;
initializeWorkers(workerNum);
}private void initializeWorkers(intnum){for(int i = 0 ; i < num ; i++){
Worker worker= newWorker() ;
workers.add(worker) ;
Thread t= new Thread(worker, "ThreadPool-worker-"+threadNum.incrementAndGet()) ;
t.start();
}
}
@Overridepublic voidexecute(Task task) {if(task!=null){synchronized(jobs){
jobs.addLast(task);//通知
jobs.notify();
}
}
}
@Overridepublic voidshutdown() {for(Worker worker : workers){
worker.shutdown();
}
}
@Overridepublic void addWorker(intnum) {//这里是否应该选择workers为监视器锁
synchronized(workers){//判断新增的数量是否超出线程池的内置规则
if(num+this.workerNum >MAX_WORKER_NUMBERS){
num= MAX_WORKER_NUMBERS - this.workerNum ;
}
initializeWorkers(num);this.workerNum +=num ;
}
}
@Overridepublic void removeWorker(intnum) {synchronized(workers){if(num >= this.workerNum){throw new IllegalArgumentException("beyond workNum") ;
}for(int i = 0 ; i < num ; i++){
Worker worker=workers.get(i);if(workers.remove(worker)){
worker.shutdown();
}
}this.workerNum -=num ;
}
}
@Overridepublic intgetTaskSize() {returnjobs.size();
}class Worker implementsRunnable{private volatile booleanrunning ;
@Overridepublic voidrun() {while(running){
Task job= null;synchronized(jobs){//如果任务列表是空的,那么就wait
if(jobs.isEmpty()){try{
jobs.wait();
}catch(InterruptedException e) {//感知到外部对WorderThread的中断操作。返回
Thread.currentThread().interrupt();return;
}
}
job=jobs.removeFirst() ;
}if(job!=null){try{
job.run();
}catch(Exception e) {//忽略job执行中的exception
}
}
}//while end
}//run end
public voidshutdown(){
running= false;
}
}
}