在使用线程时,可以这样创建一个线程池:
ExecutorService executorService= Executors.newCachedThreadPool();
executorService.execute(()-> System.out.println("run ..."));
查看下java.util.concurrent.Executors源码,可以发现有四种创建线程池的方法,分别为:newCacbedThreadPool、newFixedThreadPool、newScheduledThreadPool、newSingleThreadExecutor,其实这四种创建线程池的方法都是有ThreadPoolExecutor来实现的。源码结构图如下:
下面来分别看一下这四种线程池:
一、newCacheThreadPool
为每一个任务创建一个线程,并且也可以重用已有的线程,无核心线程数量,超过60s的空闲线程将弃用,但是会受到系统实际内存的线程。源码如下:
/**无参构造方法*/
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
/**有参的构造方法,可以传入threadFactory*/
public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>(),
threadFactory);
}
二、newFixedThreadPool
核心线程数和最大线程数是相同的,并且无空闲线程,核心线程数无限时要求,就是可以创建固定大小的线程数量,同时阻塞队列是没有大小限制的,源码如下:
/**创建固定大小的线程数*/
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
/**创建固定大小的线程数,并可以指定threadFactory*/
public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(),
threadFactory);
}
三、newScheduledThreadPool
具有延迟和周期执行线程的线程池,固定的核心线程数,最大线程数没有限制,空闲的线程会立即启用源码如下:
/**创建固定大小的corePool*/
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
return new ScheduledThreadPoolExecutor(corePoolSize);
}
/**查看ScheduledThreadPoolExecutor类,发现是集成的ThreadPoolExecutor*/
public ScheduledThreadPoolExecutor(int corePoolSize) {
super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
new DelayedWorkQueue());
}
/**创建固定大小的corePool,并指定threadFactory*/
public static ScheduledExecutorService newScheduledThreadPool(
int corePoolSize, ThreadFactory threadFactory) {
return new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);
}
/**查看ScheduledThreadPoolExecutor类,发现是集成的ThreadPoolExecutor*/
public ScheduledThreadPoolExecutor(int corePoolSize,
ThreadFactory threadFactory) {
super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
new DelayedWorkQueue(), threadFactory);
}
四、newSingleThreadExecutor
创建只有一个的核心线程,只处理一个线程,其实并不能处理并发,源码如下:
/**无参*/
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
/**指定threadFactory*/
public static ScheduledExecutorService newSingleThreadScheduledExecutor(ThreadFactory threadFactory) {
return new DelegatedScheduledExecutorService
(new ScheduledThreadPoolExecutor(1, threadFactory));
}
以上四种创建线程池的方式,通过源码可以发现都是基于ThreadPoolExecutor类中的构造方法进行实现的。