package com.ty.thread;
importjava.util.HashSet;importjava.util.Set;importjava.util.concurrent.BlockingQueue;importjava.util.concurrent.LinkedBlockingQueue;/***@authorTaoyong
* @date 2018年5月17日
* 天下没有难敲的代码!*/
public classThreadPoolExecutor {//维护线程的list
private Set threadList = new HashSet();/** 阻塞队列是线程安全的,主要使用在生产/消费者的场景*/
private BlockingQueueblockingQueue;//线程池的工作线程数
private int poolSize = 0;//线程池的核心容量
private int coreSize = 0;private boolean shutDown = false;public ThreadPoolExecutor(intsize) {this.poolSize =size;
blockingQueue= new LinkedBlockingQueue<>(poolSize);
}public void execute(Task task) throwsInterruptedException {if(shutDown == true) {return;
}if(coreSize
blockingQueue.offer(task);
produceWorker(task);
}else{
blockingQueue.put(task);
}
}private void produceWorker(Task task) throwsInterruptedException {if(task == null) {throw new NullPointerException("非法参数:传入的task对象为空!");
}if(shutDown == true) {return;
}
Thread thread= new Thread(newWorker());
threadList.add(thread);
coreSize++;
thread.start();
}public voidshutDown() {if(threadList == null || threadList.size() == 0) {return;
}
shutDown= true;for(Thread thread: threadList) {
System.out.println(thread.getName()+ " interrupt");
thread.interrupt();
}
}/** 此内部类是实际上的工作线 worker是实现了Runnable接口的实际工作线程,通过while(true)循环从BlockingQueue中取任务执行。
**/
class Worker implementsRunnable {
@Overridepublic voidrun() {while(true && shutDown == false) {try{
blockingQueue.take().doJob();
}catch(InterruptedException e) {
e.printStackTrace();
}
}
}
}
}