线程池原理:
1.线程池管理器:用于创建并管理线程池,包括创建线程池,销毁线程池,添加新任务
2.工作线程:线程池中线程,在没有任务时处于等待状态,可以循环执行线程
3.任务接口:每个任务必须实现的接口,以供工作线程调度任务的执行,它主要规定了任务的入口,任务执行完之后的收尾工作,任务的执行状态等;
4.任务队列:用于存放没有处理的任务,提供一种缓冲机制
线程Api接口:
executorService:
线程池api
private void threadPoolExecutorTest1() throws InterruptedException {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5,
10,5, TimeUnit.SECONDS,new LinkedBlockingDeque<Runnable>());
testCommon(threadPoolExecutor);
}
private void threadPoolExecutorTest2() throws InterruptedException{
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 10,
5, TimeUnit.SECONDS, new LinkedBlockingDeque<Runnable>(3), new RejectedExecutionHandler() {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
System.out.println("有任务被拒绝执行了");
}
});
testCommon(threadPoolExecutor);
}