一起学JAVA之【基础篇】4种默认线程池介绍
默认线程池创建方式
java.util.concurrent 提供了一个创建线程池的工具类Executors,里面有四种常用的线程池创建方法
public class DemoThreadPool{
public static void main(String[] args){
//创建一个核心线程数和最大线程数相同的线程池
ExecutorService executorService = Executors.newFixedThreadPool(4);
executorService.execute(()->{System.out.println("this is fixed thread pool");});
//创建一个单线程的线程池
ExecutorService singleExecutor = Executors.newSingleThreadExecutor();
singleExecutor.execute(() -> System.out.println("this is single thread pool"));
//创建一个缓存线程池
ExecutorService cacheExecutor = Executors.newCachedThreadPool();
cacheExecutor.execute(()-> System.out.println("this is cache thread pool"));
//创建一个延时执行任务的线程池
ScheduledExecutorService scheduleExecutor = Executors.newScheduledThreadPool(4);
scheduleExecutor.schedule(()-> System.out.println("this is schedule thread pool"),2,TimeUnit.SECONDS);
}
}
接下来我们来看一下他们的特点
线程池名称 | 使用阻塞队列 | 特点 | ||
---|---|---|---|---|
newFixedThreadPool | LinkedBlockingQueue() | 1、核心线程数和最大线程数相同 2、由于keepAliveTime设置为0,当线程创建后会一直存在 3、由于用的是无界队列所以可能会导致OOM | ||
newSingleThreadExecutor | LinkedBlockingQueue() | 1、核心线程数和最大线程数都为1单线程 2、无界队列可能导致OOM | ||
newCachedThreadPool | SynchronousQueue() | 1、核心线程数为0,最大线程数为Integer.MAX_VALUE 2、当没任务时线程存活时间为60秒 3、使用的是0大小的队列,所以不存储任务,只做任务转发 | ||
newScheduledThreadPool | new DelayedWorkQueue() | 1、执行周期任务 2、无界队列,可能会导致OOM |
从上面可以看出他们各有各的特点,但是阿里巴巴开发守则却不推荐使用以上线程池,因为它们可能会对服务资源的浪费,所以推荐使用通过ThreadPoolExecutor自定线程池。