Java ThreadPool - Executors

Java 线程池简要-使用Executors

直接使用J.U.C包内置的工具方法

通过javadoc我们发现其实只有4组:

通过源码看本质,需要提前了解自定义线程池的方法 点这里

1.固定大小的线程池

1
2
3
4
5
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}

本质上,核心和最大线程数一致。缓存队列无限。

2.单线程线程池

1
2
3
4
5
6
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}

同上,可以理解为 newFixedThreadPool(1)

3.可缓存的线程池

1
2
3
4
5
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}

核心线程数0,最大线程数不控制,可能会复用之前创建好的线程。适合短生命周期的异步任务

4. 周期执行的线程池

1
2
3
4
5
6
7
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
return new ScheduledThreadPoolExecutor(corePoolSize);
}
public ScheduledThreadPoolExecutor(int corePoolSize) {
super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS,
new DelayedWorkQueue());
}

本质上,核心线程数是指定的,最大不限,核心在于这个缓存队列
支持周期执行任务,或者给定间隔后执行