ExecutorService executorService = Executors.newCachedThreadPool(); //一个任务创建一个线程
ExecutorService executorService2 = Executors.newSingleThreadExecutor(); //相当于大小为 1 的 FixedThreadPool
ExecutorService executorService3 = Executors.newFixedThreadPool(5); //所有任务只能使用固定大小的线程
ExecutorService executorService4 = Executors.newScheduledThreadPool(5); //创建一个定长线程池,支持定时及周期性任务执行。
用法很简单,所以尽可能看实现
newCachedThreadPool() => new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue());
newSingleThreadExecutor() => new FinalizableDelegatedExecutorService(new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue()));
newFixedThreadPool() => new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue());
newScheduledThreadPool() => new ScheduledThreadPoolExecutor(corePoolSize);
本质上都是 对 ThreadPoolExecutor方法的不同方式调用而已。
他的七个参数:
RejectedExecutionHandler, corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit, runnableTaskQueue, ThreadFactory