自定义线程池需要了解四大方法、七大参数、四种拒绝策略
1、常用的创建线程池的四大方法
(1)创建单个线程的线程池:Executors.newSingleThreadExecutor();
//源码
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
(2)创建固定大小的线程池:Executors.newFixedThreadPool(5);
//源码
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
(3)创建不固定大小的缓存线程池:Executors.newCachedThreadPool();
//源码
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
(4)创建周期性线程池: Executors.newScheduledThreadPool(5);
//源码
public ScheduledThreadPoolExecutor(int corePoolSize) {
super(corePoolSize, Integer.MAX_VALUE,
DEFAULT_KEEPALIVE_MILLIS, MILLISECONDS,
new DelayedWorkQueue());
}
2、四种创建线程池的方法都是调用了ThreadPoolExecutor类来创建。ThreadPoolExecutor有哪七大参数?
//ThreadPoolExecutor类的构造函数
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
}
- int corePoolSize 线程池的基本大小
- int maximumPoolSize 允许的最大线程数(1、CPU密集型 2、IO密集型)
- long keepAliveTime 线程池中空闲线程等待工作的超时时间
- TimeUnit unit 时间单位
- BlockingQueue workQueue 阻塞队列,存放等待的任务
- ThreadFactory threadFactory 线程工厂,默认一般不用改
- RejectedExecutionHandler handler 拒绝策略
3、四种拒绝策略
(1)线程数量达到上限,直接抛出异常,也是默认的拒绝策略: ThreadPoolExecutor.AbortPolicy()
(2)线程数量达到上限,把任务队列中的任务放在调用者线程当中运行: ThreadPoolExecutor.CallerRunsPolicy()
(3)线程数量达到上限,会默默丢弃无法处理的任务,不予任何处理: ThreadPoolExecutor.DiscardPolicy()
(4)线程数量达到上限,丢弃最先被添加进去的任务,并尝试再次提交: ThreadPoolExecutor.DiscardOldestPolicy()
四种创建线程池方法的参数对比:
\ | corePoolSize | maximumPoolSize | keepAliveTime | TimeUnit | BlockingQueue | ThreadFactory | RejectedExecutionHandler |
---|---|---|---|---|---|---|---|
Executors.newSingleThreadExecutor() | 1 | 1 | 0L | TimeUnit.MILLISECONDS | LinkedBlockingQueue(Integer.MAX_VALUE) | Executors.defaultThreadFactory() | new AbortPolicy() |
Executors.newFixedThreadPool(5) | 5 | 5 | 0L | TimeUnit.MILLISECONDS | LinkedBlockingQueue(Integer.MAX_VALUE) | Executors.defaultThreadFactory() | new AbortPolicy() |
Executors.newCachedThreadPool() | 0 | Integer.MAX_VALUE | 60L | TimeUnit.MILLISECONDS | SynchronousQueue(false) | Executors.defaultThreadFactory() | new AbortPolicy() |
Executors.newScheduledThreadPool(5) | 5 | Integer.MAX_VALUE | DEFAULT_KEEPALIVE_MILLIS = 10L | MILLISECONDS | DelayedWorkQueue() | Executors.defaultThreadFactory() | new AbortPolicy() |
4、看到这里大家应该都知道如何自定义创建线程池了吧!可以通过直接调用ThreadPooExecutor类进行创建。
只要保持微笑,生活也会为你抹去眼角的泪水!
版权声明:本文为Sponge_boy原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。