拒绝策略:
- new ThreadPoolExecutor.AbortPolicy() // 达到线程池线程最大数时,拒绝新任务,抛出异常
- new ThreadPoolExecutor.CallerRunsPolicy() // 不丢弃任务,将任务交由该任务提交者的线程执行,相当于没有开启子线程
- new ThreadPoolExecutor.DiscardPolicy() //直接丢掉任务,不会抛出异常
- new ThreadPoolExecutor.DiscardOldestPolicy() //队列满了,丢弃最早的任务,不会抛出异常
超时时间:在核心线程池大小和最大线程池大小之间的空闲线程最大存活的时间。等待队列满了后,在没有达到最大线程池大小条件下,又新建了线程,而这些线程任务结束后,并不会杀掉线程资源,还会存活一段时间,这个时间就是超时时间
ExecutorService threadPool = new ThreadPoolExecutor(
2,
Runtime.getRuntime().availableProcessors(),
3,
TimeUnit.SECONDS,
new LinkedBlockingDeque<>(3),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.DiscardOldestPolicy());
try {
for (int i = 1; i <= 9; i++) {
// execute里可以传入实现Runnable接口的类的对象
threadPool.execute(()-> System.out.println(Thread.currentThread().getName()+" ok"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
threadPool.shutdown();
}
预制线程池:
Executors.newCachedThreadPool()
ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
Executors.newFixedThreadPool(3)
ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
Executors.newSingleThreadExecutor()
ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>())