创建固定大小的线程池
ExecutorService executorService = Executors. newFixedThreadPool ( 5 ) ;
创建单个线程的线程池
ExecutorService executorService = Executors. newSingleThreadExecutor ( ) ;
创建可缓存线程池
ExecutorService executorService = Executors. newCachedThreadPool ( ) ;
自定义线程池
ExecutorService pool = new ThreadPoolExecutor ( 2 , 5 , 3 , TimeUnit. SECONDS,
new LinkedBlockingDeque < > ( 3 ) ,
Executors. defaultThreadFactory ( ) ,
new ThreadPoolExecutor. DiscardOldestPolicy ( ) ) ;
7大参数说明:类比银行
核心线程数:开放窗口的数量; 最大线程数:一共有多少个处理窗口; 等待超时时间:除核心线程外,其余的线程没有任务处理时,超过等待时间自动关闭线程; 时间单位; 阻塞队列:银行的座位数量; 创建线程的工厂; 四种拒绝策略:
new ThreadPoolExecutor. AbortPolicy ( ) ;
new ThreadPoolExecutor. CallerRunsPolicy ( ) ;
new ThreadPoolExecutor. DiscardPolicy ( ) ;
new ThreadPoolExecutor. DiscardOldestPolicy ( ) ;