public class ThreadPoolTest { public static void main(String[] args) { /** * * 核心线程数量:0 * 非核心线程数量:Integer.MAX_VALUE * 队列:SynchronousQueue * * 当有大量任务时,就会一直创建线程,这样可能会导致cpu达到100% * return new ThreadPoolExecutor(0, Integer.MAX_VALUE, * 60L, TimeUnit.SECONDS, * new SynchronousQueue<Runnable>()); */ ExecutorService executorService = Executors.newCachedThreadPool(); /** * 核心线程数量:1 * 非核心线程数量: 1-1 = 0 * 队列:LinkedBlockingQueue (容量为Integer.MAX_VALUE) * * 当有大量任务时,由于线程数量固定,来不及处理的任务就会放入队列(容量大小可视为无限制),这样可能会导致内存溢出 * public LinkedBlockingQueue() { * this(Integer.MAX_VALUE); * } * * return new FinalizableDelegatedExecutorService * (new ThreadPoolExecutor(1, 1, * 0L, TimeUnit.MILLISECONDS, * new LinkedBlockingQueue<Runnable>())); */ ExecutorService executorService1 = Executors.newSingleThreadExecutor(); /** * 核心线程数量为:nThreads * 非核心线程数量为: nThreads-nThreads = 0 * 队列:LinkedBlockingQueue(容量为Integer.MAX_VALUE) * * 当有大量任务时,由于线程数量固定,来不及处理的任务就会放入队列(容量大小可视为无限制),这样可能会导致内存溢出 * return new ThreadPoolExecutor(nThreads, nThreads, * 0L, TimeUnit.MILLISECONDS, * new LinkedBlockingQueue<Runnable>()); */ ExecutorService executorService2 = Executors.newFixedThreadPool(10); /** * 自定义线程池 * * 核心线程数量:10 * 非核心线程数量:20 - 10 = 10 * 队列:ArrayBlockingQueue(容量指定为10) * * 假设当前同时产生50个任务,每个任务需要执行10分钟(线程需要被占用10分钟才可以再分配任务)。 * * 先会将1-10任务分配给核心线程 * 然后将11-20任务分配给队列 * 再将21-30任务分配给非核心线程 * * 此时,核心线程、非核心线程、队列都已经满了 * 剩下的任务将会被拒绝... * * 分配优先级:核心线程->队列->非核心线程 * 执行优先级:核心线程->非核心线程->队列 */ ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10, 20, 0, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(10)); } }