1. 线程池
Executor 接口,ExecutorService 接口 AbstractExecutorService ThreadPoolExecutor
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory) {
...
}
- corePoolSize 核心线程数量
- maximumPoolSize 最大线程数量
- keepAliveTime 非核心线程空闲时等待下一个任务的时间
- unit 指的是 keepAliveTime 的单位
- workQueue 任务队列
- threadFactory 线程工厂,设置 thread 相关参数
·
执行流程
- execute 一个线程后,如果核心线程未满,则启用核心线程执行
- 如果核心线程满了且 workQueue 未满,则把新线程放入 workQueue 中等待
- 如果 核心线程满了且 workQueue 也满了,则开启非核心线程执行任务
- 如果线程数比非核心线程数还多,则拒绝执行,根据拒绝策略执行相应逻辑
常用线程池
- FixedThreadPool
只有核心线程 且 队列无上限
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
- CachedThreadPool
无核心线程,非核心线程数量为Integer.MAX_VALUE,任务队列为 SynchronousQueue
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
- SingleThreadPool
只有一个核心线程,队列无限
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
- ScheduledThreadPool
延时启动的线程池
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
return new ScheduledThreadPoolExecutor(corePoolSize);
}
public ScheduledThreadPoolExecutor(int corePoolSize) {
super(corePoolSize, Integer.MAX_VALUE,
DEFAULT_KEEPALIVE_MILLIS, MILLISECONDS,
new DelayedWorkQueue());
}