线程池ThreadPoolExecutor的继承关系:
想知道有哪些参数,先看参数最多的构造函数:
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
if (corePoolSize < ||
maximumPoolSize <= ||
maximumPoolSize < corePoolSize ||
keepAliveTime < )
throw new IllegalArgumentException();
if (workQueue == null || threadFactory == null || handler == null)
throw new NullPointerException();
this.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.workQueue = workQueue;
this.keepAliveTime = unit.toNanos(keepAliveTime);
this.threadFactory = threadFactory;
this.handler = handler;
}
可以看到创建一个线程池需要七个参数。
线程工厂ThreadFactor,线程池中默认给定了一个线程工厂DefaultThreadFactory,线程工厂的作用是用于创建线程,自己创建线程工厂时需要实现ThreadFactor接口,该接口中只有一个方法Thread newThread(Runnable r);,即创建线程的方法,自定义线程工厂的好处是可以自定义线程名称。
阻塞队列BlockingQueue,阻塞队列是在核心线程满了以后存放任务使用,常用的有LinkedBlockingQueue、ArrayBlockingQueue、SynchronousQueue、DelayedWorkQueue等,当阻塞队列也满时,会创建线程至最大线程数,如果队列已满,也达到最大线程数,则执行拒绝策略。
拒绝策略RejectedExecutionHandler:
RejectedExecutionException,默认使用该策略。查看源码:
public static class DiscardPolicy implements RejectedExecutionHandler {
public DiscardPolicy() { }
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
}
}
public static class DiscardOldestPolicy implements RejectedExecutionHandler {
public DiscardOldestPolicy() { }
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
if (!e.isShutdown()) {
e.getQueue().poll();
e.execute(r);
}
}
}
public static class AbortPolicy implements RejectedExecutionHandler {
public AbortPolicy() { }
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
throw new RejectedExecutionException("Task " + r.toString() +
" rejected from " +
e.toString());
}
}
public static class CallerRunsPolicy implements RejectedExecutionHandler {
public CallerRunsPolicy() { }
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
if (!e.isShutdown()) {
r.run();
}
}
}
如果想要实现自己的拒绝策略,那么实现RejectedExecutionHandler接口即可。
如下图:
查看源码执行流程,execute()方法:
public void execute(Runnable command) {
//传入的任务是否为空
if (command == null)
throw new NullPointerException();
/*
* Proceed in 3 steps:
*
* 1. 如果运行的线程数小于corePoolSize,则创建新的线程(线程池状态为正在运行的状态)。
*
* 2. 如果任务排队成功,仍然需要检查线程池的状态,如果不是可运行的状态则回滚刚刚的操作。
*
* 3. 如果排队失败,则尝试添加新的线程,如果已经达到线程池最大数量,则执行拒绝策略。
*/
//判断线程数是否小于核心线程数
int c = ctl.get();
if (workerCountOf(c) < corePoolSize) {
//如果小于,新增一个线程来执行
if (addWorker(command, true))
return;
c = ctl.get();
}
//如果核心线程数已满,则向阻塞队列中添加任务
if (isRunning(c) && workQueue.offer(command)) {
int recheck = ctl.get();
if (! isRunning(recheck) && remove(command))
reject(command);
else if (workerCountOf(recheck) == )
addWorker(null, false);
}
//如果添加失败,则创建线程至最大值
else if (!addWorker(command, false))
//如果创建失败,则执行拒绝策略
reject(command);
}
查看源码,发现线程池有五种状态,如下:
// runState is stored in the high-order bits
private static final int RUNNING = -1 << COUNT_BITS;
private static final int SHUTDOWN = << COUNT_BITS;
private static final int STOP = 1 << COUNT_BITS;
private static final int TIDYING = 2 << COUNT_BITS;
private static final int TERMINATED = 3 << COUNT_BITS;
shutdown()方法后进入此状态,继续处理队列中的任务,但是不再接收新的任务。shutdownNow()方法后进入此状态,不处理队列中的任务,也不接收新的任务。terminated()方法,进入销毁状态。terminated()方法,进入此状态。状态转换如下图:
Executors提供了几种快速创建的线程池:
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
return new ScheduledThreadPoolExecutor(corePoolSize);
}
public ScheduledThreadPoolExecutor(int corePoolSize) {
super(corePoolSize, Integer.MAX_VALUE, , NANOSECONDS,
new DelayedWorkQueue());
}
public static ScheduledExecutorService newSingleThreadScheduledExecutor() {
return new DelegatedScheduledExecutorService
(new ScheduledThreadPoolExecutor(1));
}
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/70000523/viewspace-3133987/ ,如需转载,请注明出处,否则将追究法律责任。