Executors
Executors是concurrent包下的工具类,通过静态方法产生各种线程池
- 产生固定线程数量的线程池
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
- 产生只有一个线程的线程池
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
- 产生具有缓存能力的线程池,如果任务数量超过能力,可回收利用空闲的线程
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
- 产生具有定时任务或周期性任务的线程池
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
return new ScheduledThreadPoolExecutor(corePoolSize);
}
ThreadPoolExecutor
ThreadPoolExecutor是真正的线程池,构造方法有若干个参数
public ThreadPoolExecutor(
int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler)
- corePoolSize:
核心线程数,当前任务数量小于corePoolSize时,直接创建线程执行,当空闲时也不会被回收 - maximumPoolSize:
最大线程数,当workQueue已满,并且maximumPoolSize>corePoolSize创建线程执行 - keepAliveTime:
超过核心线程数量的线程的存活时间 - unit:
超过核心线程数量的线程的存活时间的单位 - workQueue:
任务等待队列 - threadFactory:
线程工厂 - handler:
异常处理策略,默认AbortPolicy,抛出异常
创建线程是调用addWorker方法,其核心是调用ThreadFactor产生一个线程
w = new Worker(firstTask);
final Thread t = w.thread;
private final class Worker extends AbstractQueuedSynchronizer implements Runnable {
final Thread thread;
Runnable firstTask;
volatile long completedTasks;
Worker(Runnable firstTask) {
setState(-1); // inhibit interrupts until runWorker
this.firstTask = firstTask;
this.thread = getThreadFactory().newThread(this);
}
}
创建线程池如果不传入自定义线程工厂,会用默认的工厂
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
Executors.defaultThreadFactory(), defaultHandler);
}
在defaultThreadFactory函数中直接new了一个线程
public Thread newThread(Runnable r) {
Thread t = new Thread(group, r,namePrefix + threadNumber.getAndIncrement(), 0);
return t;
}
ScheduledThreadPoolExecutor
ScheduledThreadPoolExecutor继承自ThreadPoolExecutor,队列用的是delayedWorkQueue
public ScheduledThreadPoolExecutor(int corePoolSize) {
super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
new DelayedWorkQueue());
}
加入任务时,会加入到延迟队列中,如果任务到达时间,就执行,否则阻塞