java线程池的工作原理这里不做展开,这里主要要解释的是,线程池创建后,核心线程是否已经创建了
测试代码:
public static void main(String[] args) {
ThreadPoolExecutor executorOne = new ThreadPoolExecutor(10, 20,
1L, TimeUnit.MINUTES,
new LinkedBlockingQueue<>());
System.out.println("当前线程池线程数:" + executorOne.getPoolSize());
executorOne.prestartCoreThread();
System.out.println("当前线程池线程数:" + executorOne.getPoolSize());
System.out.println(executorOne.prestartAllCoreThreads());
System.out.println("当前线程池线程数:" + executorOne.getPoolSize());
executorOne.shutdown();
}
运行结果:
运行结果分析:
1、第一行打印结果0,说明线程池创建时,核心线程并不会被立马创建;
2、prestartCoreThread(),会给线程池初始化1个线程;
3、prestartAllCoreThreads(),会给线程池创建线程池的核心线程数配置大小的线程数,也就是10个,第三行输出9,是因为前面prestartCoreThread()已经创建了1个线程,prestartAllCoreThreads()只创建9个线程,就达到核心线程数的配置10个了,因此只创建了9个线程;
总结:
线程池创建时,核心线程并不会被立马创建,可以通过调用prestartCoreThread()和prestartAllCoreThreads()为线程池初始化好核心线程;
当然,实际使用线程池时,一般在任务提交给线程池时再创建核心线程基本就满足需要了。