ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, handler)
1.参数含义
corePoolSize:线程池最小数量
maximumPoolSize:线程池最大数量
keepAliveTime:当线程数量超过corePoolSize,额外的线程超过keepAliveTime会被终止掉
unit:时间单元,TimeUnit.Secondes,TimeUnit.Days等
workQueue:队列,ArrayBlockingQueue(定长队列),LinkedBlockingQueue(无界队列)
handler:拒绝策略(当线程数量超过队列可存放的数量时,怎么处理,后面会涉及四种拒绝策略)
1)Executors.newCachedThreadPool:可缓存线程池
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
2)Executors.newFixedThreadPool:定长线程池
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
3)Executors.newSingleThreadExecutor:单个线程,保证线程按照指定顺序(FIFO,LIFO,优先级)执行
public ScheduledThreadPoolExecutor(int corePoolSize) {
super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
new DelayedWorkQueue());
}
4)Executors.newScheduledThreadPool:定长可周期执行的线程池
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
return new ScheduledThreadPoolExecutor(corePoolSize);
}
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
2.拒绝策略
1)new ThreadPoolExecutor.AbortPolicy():抛弃,并报出异常RejectedExecutionException
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
throw new RejectedExecutionException("Task " + r.toString() +
" rejected from " +
e.toString());
}
2)new ThreadPoolExecutor.CallerRunsPolicy():在executor shutdown之前,重复调用自己
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
if (!e.isShutdown()) {
r.run();
}
}
3)new ThreadPoolExecutor.DiscardPolicy():无声的抛弃
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
}
4)new ThreadPoolExecutor.DiscardOldestPolicy():对拒绝任务不抛弃,而是抛弃队列中等待最久的任务,将拒绝任务加入队列中
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
if (!e.isShutdown()) {
e.getQueue().poll();
e.execute(r);
}
}
3.线程池使用优先级
通过execute(Runnable)新加入任务,优先级corePoolSize>workQueue>maximumPoolSize
1)如果当前线程<corePoolSize,则新建线程处理新添加的任务
2)如果此时线程池中数量=corePoolSize,缓冲队列未满,则该任务被放入缓冲队列
3)当>corePoolSize,缓冲队列已满,并且<maximumPoolSize,则新建线程处理被添加的任务
4)当此时线程池中数量>corePoolSize,队列已满,=maximumPoolSize,则利用拒绝策略处理新添加任务
4.线程池的停止(源码待学习)
1)shutdown():线程池状态变成shutdown,不能再往线程池中添加任务,等到池中所有的任务执行完,则线程池停止。
2)shutdownNow():线程池状态变为stop,尝试停止正在执行的线程,队列中的任务停止。
5.execute(Runnable)和submit(Callable/Runnable)方法
2)submit可以有返回值
submit(Runnable) ,虽然有Future<?>返回值,但是返回值为空,因为Runnable中的run方法为void
submit(Runnable, T result>,Future中可以获取result的信息
submit(Callable),有返回值,因为Callable中的call方法有返回值