什么是线程池?
Thread POOL ,就是将多个线程放入一个池子中,是一种多线程形式,它可以实现线程复用,控制最大的并发数,以及管理线程的整个生命周期。
为什么需要线程池?
频繁的创建和销毁线程非常耗费性能,因为在JAVA中创建一个线程需要调用操作系统的API
Executors 为我们提供了几种创建线程的方式:
newFixedThreadPool
newSingleThreadExecutor:只会创建一个工作线程来处理任务
newCachedThreadPool
newScheduledThreadPool
线程的7个参数
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;
}
corePoolSize:核心线程数,池中要保留的线程数,偶数
maximumPoolSize:允许的最大线程数
keepAliveTime:线程数大于核心,这是多余空闲线程的最长时间将在终止前等待新任务。
unit: keepAliveTime参数的时间单位
workQueue:任务队列,在任务完成之前用于保存任务的队列,阻塞队列
threadFactory:线程工厂
RejectedExecutionHandler :拒绝策略,阻止执行时要使用的处理程序,因为达到了线程边界和队列容量