// Executors类提供了一些static方法来创建各种用途的线程池// 只有核心线程// 任务阻塞队列是无界的publicstaticExecutorServicenewFixedThreadPool(int nThreads){returnnewThreadPoolExecutor(nThreads, nThreads,0L,TimeUnit.MILLISECONDS,newLinkedBlockingQueue<Runnable>());}// 只有非核心线程// 非核心线程的空闲生存时间是60s// SynchronousQueue阻塞队列(这个队列没有容量,插入的时候会阻塞,直到另一个线程来取,才停止阻塞)publicstaticExecutorServicenewCachedThreadPool(){returnnewThreadPoolExecutor(0,Integer.MAX_VALUE,60L,TimeUnit.SECONDS,newSynchronousQueue<Runnable>());}// 只有一个核心线程// 使用场景:希望多个任务排队执行// Unlike the otherwise equivalent {@code newFixedThreadPool(1)} the returned executor is// guaranteed not to be reconfigurable to use additional threads.publicstaticExecutorServicenewSingleThreadExecutor(){// 不直接返回ThreadPoolExecutor对象,避免出去之后可以强转为ThreadPoolExecutor,调用它的特有方法// 装饰器模式(限制了ThreadPoolExecutor类中一些特有方法的暴露,只有ExecutorService中定义的方法)returnnewFinalizableDelegatedExecutorService(newThreadPoolExecutor(1,1,0L,TimeUnit.MILLISECONDS,newLinkedBlockingQueue<Runnable>()));}
// 不是RUNNING状态的线程池,都会返回TRUEbooleanisShutdown();// 执行后,线程池状态变为SHUTDOWN// 调用此方法不会阻塞调用该方法的线程的执行// 主线程不会等线程池中的线程执行完毕才执行shutdown()后面的代码voidshutdown();// ExecutorService接口// 执行后,线程池状态变为STOP// 用interrupt的方式打断正在执行的任务// 返回任务队列中的任务List<Runnable>shutdownNow();// ExecutorService接口// 调用shutdown()后,主线程不会等线程池中线程结束,如果想在线程池TERMINATED后做些事情,可以使用此方法等待// Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs// or the current thread is interrupted, whichever happens first.booleanawaitTermination(long timeout,TimeUnit unit);// ExecutorService接口