线程池的好处:
1
、降低资源的消耗
2
、提高响应的速度
3
、方便管理。
线程池:三大方法、7大参数、4种拒绝策略
三大方法
1、创建单个线程
ExecutorService threadPool1= Executors.newSingleThreadExecutor();//单个线程
2、创建一个固定大小的线程池
ExecutorService threadPool2= Executors.newFixedThreadPool(5);//创建一个固定大小的线程池
3、创建一个可伸缩的线程池
ExecutorService threadPool3=Executors.newCachedThreadPool();//可伸缩的,遇强则强,遇弱则弱。
7大参数
查看源码可以发现,这个三个方法本质上都是一样的,都是创建了一个ThreadPoolExecutor。
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
其中重要的是ThreadPoolExecutor的七个参数
public ThreadPoolExecutor( // 核心线程池大小
int corePoolSize,
// 最大核心线程池大小
int maximumPoolSize,
//超时等待时间
long keepAliveTime,
//超时单位
TimeUnit unit,
//阻塞队列
BlockingQueue<Runnable> workQueue,
// 线程工厂:创建线程的,一般不用动
ThreadFactory threadFactory,
//拒绝策略
RejectedExecutionHandler handler) {
if (corePoolSize < 0 ||
maximumPoolSize <= 0 ||
maximumPoolSize < corePoolSize ||
keepAliveTime < 0)
throw new IllegalArgumentException();
if (workQueue == null || threadFactory == null || handler == null)
throw new NullPointerException();
this.acc = System.getSecurityManager() == null ?
null :
AccessController.getContext();
this.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.workQueue = workQueue;
this.keepAliveTime = unit.toNanos(keepAliveTime);
this.threadFactory = threadFactory;
this.handler = handler;
}
四种拒绝策略
/*** new ThreadPoolExecutor.AbortPolicy() // 最大线程数量已经满了,这时候还有线程进来 来,不处理这个进程的,抛出异常* new ThreadPoolExecutor.CallerRunsPolicy() // 哪来的去哪里!* new ThreadPoolExecutor.DiscardPolicy() // 队列满了,丢掉任务,不会抛出异常!* new ThreadPoolExecutor.DiscardOldestPolicy() // 队列满了,尝试去和最早的竞争,也不会抛出异常!*/
银行办理业务例子
银行办可以看成是一个线程池,每一个办理业务的柜台可以看成是一个线程。一般工作的就是核心线程,如果需要办理的任务大于核心线程,那么就让这个任务进入阻塞队列中进行等待。阻塞队列分为两种:
1、无边界的阻塞队列
2、有边界的阻塞队列
对于无边界的阻塞队列,任务可以无限加,对于有边界的阻塞队列,如果达到队列的最大值,就会增加线程池中可以工作的线程的数量,如果这个工作线程的数量超过设定好的最大值的时候,就会采用拒绝策略,