线程池底层实现
线程池的底层实现是:ThreadPoolExecutor
使用工厂类Executors快速创建预定义线程池
IDEA插件Alibaba Java Coding Guidelines,代码提示如下(马云不推荐使用啊)
线程池不允许使用 Executors 去创建,而是通过 ThreadPoolExecutor 的方式,这样的处理方式让写的同学更加明确线程池的运行规则,规避资源耗尽的风险。
说明:Executors 返回的线程池对象的弊端如下:
1) FixedThreadPool 和 SingleThreadPool:
允许的请求队列长度为 Integer.MAX_VALUE(无限),可能会堆积大量的请求,从而导致 OOM。
2) CachedThreadPool:
允许的创建线程数量为 Integer.MAX_VALUE(无限),可能会创建大量的线程,从而导致 OOM。
预定义线程池
1. FixedThreadPool(典型的无限队列线程池)
允许的请求队列长度为 Integer.MAX_VALUE(无限),可能会堆积大量的请求,从而导致 OOM。
ExecutorService executorService = Executors.newFixedThreadPool(10);
//点击进入代码,查看实现:
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
第一种写法(最简洁):使用工厂类Executors快速创建线程池
ExecutorService executorService = Executors.newFixedThreadPool(10);
第二种写法(最原始):使用ThreadPoolExecutor自定义线程池
ExecutorService pool = new ThreadPoolExecutor(
10, // corePoolSize = 10
10, // maximumPoolSize = 10
0L, // keepAliveTime = 0
TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(), // 队列默认大小:2147483647
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy());
第三种写法(适中):使用ThreadPoolTaskExecutor更简洁的写法,创建线程池
ThreadPoolTaskExecutor poolTaskExecutor = new ThreadPoolTaskExecutor();
poolTaskExecutor.setQueueCapacity(Integer.MAX_VALUE); // Integer.MAX_VALUE = 2147483647
poolTaskExecutor.setCorePoolSize(10);
poolTaskExecutor.setMaxPoolSize(10);
poolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
poolTaskExecutor.setKeepAliveSeconds(0);
poolTaskExecutor.initialize();
以上三种写法,实现的功能一模一样