创建线程池有哪几种方式

一、Executors

Executors是一个线程相关的工具类。主要提供了以下几种创建线程池的方法:

index method corePoolSize maximumPoolSize keepAliveTime unit workQueue 1 newCachedThreadPool 0 Integer.MAX_VALUE 60L TimeUnit.SECONDS SynchronousQueue 2 newFixedThreadPool 自定义 与corePoolSize相同 0L TimeUnit.MILLISECONDS LinkedBlockingQueue 3 newSingleThreadExecutor 1 1 0L TimeUnit.MILLISECONDS LinkedBlockingQueue 4 newScheduledThreadPool 自定义 Integer.MAX_VALUE 0 NANOSECONDS DelayedWorkQueue 5 newSingleThreadScheduledExecutor 1 Integer.MAX_VALUE 0 NANOSECONDS DelayedWorkQueue

第1,4,5种:线程最大数量是Integer.MAX_VALUE,当执行大量耗时任务时,容易造成堆外内存溢出 第2,3种:使用的的阻塞队列为无边界队列,当任务量过大时,可能会导致内存溢出

注意: 在java8中新添加了newWorkStealingPool,

二、ThreadPoolExecutor

ThreadPoolExecutor(int corePoolSize, //核心线程数量
                   int maximumPoolSize, // 最大线程数量
                   long keepAliveTime, // 存活时间 
                   TimeUnit unit, // 时间单位
                   BlockingQueue<Runnable> workQueue, //阻塞队列
                   ThreadFactory threadFactory) // 拒绝策略

注意: 有多于corePoolSize但小于maximumPoolSize线程正在运行,则仅当队列已满时才会创建新线程

经验分享 程序员 微信小程序 职场和发展