2、ThreadPoolExecutor
1)线程池状态
ThreadPoolExecutor使用int的高3位表示线程池状态,低29位表示线程数量
状态名 | 高3位 | 接收新任务 | 处理阻塞队列任务 | 说明 |
---|---|---|---|---|
RUNNING | 111 | Y | Y | |
SHUTDOWN | 000 | N | Y | 不会接收新任务,但会处理阻塞队列剩余任务 |
STOP | 001 | N | N | 会中断正在执行的任务,并抛弃阻塞队列任务 |
TIDYING | 010 | - | - | 任务全部执行完毕,活动现场为0即进入终结 |
TERMINATED | 011 | - | - | 终结状态 |
从数字上比较,TERMINATED>TIDYING>STOP>SHUTDOWN>RUNNING
这些信息存储在一个原子变量ctl中,目的是将线程池状态与线程个数合二为一,这样就可以用一次cas原子操作进行赋值
// c 为旧值,ctlOf返回结果为新值
ctl.compareAndSet(c, ctlOf(targetState, workCountOf(c)));
// rs为高3位代表线程池状态,wc为低29位,代表线程个数,ctl是合并他们
private static ctlOf(int rs. int wc) {return rs | wc;}
2)构造方法
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler)
- corePoolSize 核心线程数(最多保留的线程数)
- maximumPoolSize 最大线程数
- keepAliveTime 生存时间-针对救急线程
- unit 时间单位-针对救急线程
- workQueue 阻塞队列
- threadFactory 线程工厂 - 可以为线程创建时起一个好名字
- handler 拒绝策略
工作方式:
- 线程池中刚开始没有线程,当一个任务提交给线程池后,线程池会创建一个新的线程来执行任务
- 当线程数达到corePoolSize并没有线程空闲,这时候再加入任务,新加的任务会被加入到workQueue队列排队,知道有空闲的线程
- 如果队列选择了游街队列,那么任务超过了队列大小时,会创建maximumPoolSize - corePoolSize数目的线程来救急。
- 如果线程到达maximumPoolSize后仍然有新任务,这时会执行拒绝策略。拒绝策略java提供了4种实现,其他著名框架也提供了实现
- AbortPolicy 让调用者抛出RejectdExecutionException异常,这是默认策略
- CallerRunsPolicy 让调用者运行任务
- DiscardPolicy 放弃本次任务
- DiscardOldestPolicy 放弃队列中最早的任务,本任务取而代之
- Dubbo实现,在抛出RejectdExecutionException异常之前会记录日志,并dump线程栈的信息,方便定位问题
- Netty实现,是创建一个新线程来执行任务
- ActiveMQ实现,带超时等待(60s)尝试放入队列,类似自定义的拒绝策略
- PinPoint实现,使用了一个拒绝策略链,会逐一尝试策略链中的每种拒绝策略
- 当高峰过去后,超过corePoolSize的救急线程如果一段时间没有任务做,需要结束节省资源,这个时间由keepAliveTime和unit来控制
根据这个构造的方法,JDK Executors类中提供了众多工厂方法来创建各种用途的线程池
3)newFixedThreadPool
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
特点:
- 核心线程数 == 最大线程数 (没有救急线程被创建),因此也无需等待超时时间
- 阻塞队列是无界的,可以放任意数量的任务
评价:适用于任务量已知,相对耗时的任务
4)newCachedThreadPool
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
特点
- 核心线程数是0,最大线程数是Integer.Max_VALUE,救急线程的空闲生存时间是60s,意味着
- 全部都是救急线程(60s后可以回收)
- 救急线程可以无线创建
- 队列采用了SynchronousQueue实现,特点是,他没有容量,没有线程来是放不进去的(一手交钱、一手交货)
public static void main(String[] args) throws InterruptedException {
Executors.newCachedThreadPool();
SynchronousQueue<Integer> synchronousQueue = new SynchronousQueue<>();
new Thread(() -> {
try {
log.debug("putting...{}", 1);
synchronousQueue.put(1);
log.debug("{}put...", 1);
log.debug("putting...{}", 2);
synchronousQueue.put(2);
log.debug("{}put...", 2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "t1").start();
Thread.sleep(1000);
new Thread(() -> {
try {
log.debug("taking{}", 1);
synchronousQueue.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "t2").start();
Thread.sleep(1000);
new Thread(() -> {
try {
log.debug("taking{}", 2);
synchronousQueue.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "t3").start();
}
输出
2022/03/26-13:47:05.776 [t1] c.Test2 - putting...1
2022/03/26-13:47:06.780 [t2] c.Test2 - taking1
2022/03/26-13:47:06.780 [t1] c.Test2 - 1put...
2022/03/26-13:47:06.780 [t1] c.Test2 - putting...2
2022/03/26-13:47:07.789 [t3] c.Test2 - taking2
2022/03/26-13:47:07.789 [t1] c.Test2 - 2put...
评价:整个线程池表现为线程数会根据任务量不断增长,没有上限,当任务执行完毕,空闲1分钟后释放线程。是和任务数比较密集,但每个任务执行时间较短的情况。
5)newSingleThreadExecutor
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
使用场景:
希望多个任务排队执行。线程数固定为1,任务多于1时,会放入无界队列排队。任务执行完毕,这唯一的线程也不会被释放。
区别:
- 自己创建一个单线程串行执行任务,如果执行失败而终止也没有任何补救措施,而线程池还会新建一个线程,奥正线程池的正常工作
- Executors.newSingleThreadExecutor()线程数始终为1,不能修改
- FinalizableDelegatedExecutorService应用是装饰器模式,只对外暴露了ExecutorService接口,因此不能调用ThreadPoolExecutor中特有的方法
- Executors.newFixedThreadPool(1)初始时为1,以后还可以修改
- 对外暴露的是ThreadPoolExecutor 对象,可以强转后调用setCorePoolSize等方法进行修改
6)提交任务
// 执行任务
void execute(Runnable command);
//提交任务task,用返回值Future获得任务执行结果
<T> Future<T> submit(Callable<T> task);
//提交tasks中所有任务
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) throw InterruptedException;
//提交tasks中所有任务,带超时时间
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throw InterruptedException;
//提交tasks中所有任务,哪个任务先执行完毕,返回此任务执行结果,其他任务取消
<T> List<Future<T>> invokeAny(Collection<? extends Callable<T>> tasks) throw InterruptedException, ExecutionException;
//提交tasks中所有任务,哪个任务先执行完毕,返回此任务执行结果,其他任务取消,带超时时间
<T> List<Future<T>> invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throw InterruptedException, ExecutionException, TimeoutException;
7)关闭线程池
shutdown
/**
线程池状态变为 SHUTDOWN
- 不会接收新任务
- 但已提交任务会执行完
- 此方法不会阻塞调用线程的执行
*/
void shutdown();
public void shutdown() {
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
checkShutdownAccess();
// 修改线程池胡葬台
advanceRunState(SHUTDOWN);
// 打断空闲线程
interruptIdleWorkers();
onShutdown(); // hook for ScheduledThreadPoolExecutor 扩展点 ScheduledThreadPoolExecutor
} finally {
mainLock.unlock();
}
// 尝试终结(没有运行的线程可以立即终结,如果还有运行的线程也不会等)
tryTerminate();
}
shutdownNow
/**
线程池状态为STOP
- 不会接收新任务
- 会将对俄中任务返回
- 并用interrupt的方式中断正在执行的任务
*/
public List<Runnable> shutdownNow();
public List<Runnable> shutdownNow() {
List<Runnable> tasks;
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
checkShutdownAccess();
// 修改线程池状态
advanceRunState(STOP);
// 打断所有线程
interruptWorkers();
// 获取队列中剩余任务
tasks = drainQueue();
} finally {
mainLock.unlock();
}
// 尝试终结
tryTerminate();
return tasks;
}
其他方法
// 不在RUNNING状态的线程池,就会返回true
boolean isShutdown();
// 线程好吃状态是否是TERMINATED
boolean isTerminated();
// 调用shutdown后,由于调用线程并不会等待所有线程运行结束,因此如果它想在线程池TERMINATED后做些事情,可以利用此方法等待
boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException;
8)任务调度线程池
在【任务调度线程池】功能加入之前,可以使用java.util.Timer来实现定时功能,Timer的有点在于简单易用,但由于所有任务都是由同一个线程来调度,因此所有任务都是串行执行的,同一时间只能有一个任务在执行,前一个任务的延迟或异常都将会影响到之后的任务。
public static void main(String[] args) {
Timer timer = new Timer();
TimerTask task1 = new TimerTask() {
@Override
public void run() {
log.debug("task 1");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
TimerTask task2 = new TimerTask() {
@Override
public void run() {
log.debug("task 2");
}
};
timer.schedule(task1, 1000);
timer.schedule(task2, 1000);
}
输出
2022/03/26-16:05:42.339 [Timer-0] c.Test1 - task 1
2022/03/26-16:05:44.348 [Timer-0] c.Test1 - task 2
使用ScheduledExecutorService改写:
public static void main(String[] args) {
ScheduledExecutorService pool = Executors.newScheduledThreadPool(2);
pool.schedule(() -> {
log.debug("task1");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}, 1, TimeUnit.SECONDS);
pool.schedule(() -> {
log.debug("task2");
}, 1, TimeUnit.SECONDS);
}
输出
2022/03/26-22:02:34.557 [pool-1-thread-2] c.Test1 - task2
2022/03/26-22:02:34.557 [pool-1-thread-1] c.Test1 - task1
scheduleAtFixedRate 例子:
public static void main(String[] args) {
ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);
log.debug("start...");
pool.scheduleAtFixedRate(()->{
log.debug("running...");
}, 1,1, TimeUnit.SECONDS);
}
输出
2022/03/26-22:04:01.284 [main] c.Test2 - start...
2022/03/26-22:04:02.337 [pool-1-thread-1] c.Test2 - running...
2022/03/26-22:04:03.334 [pool-1-thread-1] c.Test2 - running...
2022/03/26-22:04:04.337 [pool-1-thread-1] c.Test2 - running...
2022/03/26-22:04:05.326 [pool-1-thread-1] c.Test2 - running...
scheduleAtFixedRate 例子(执行时间超过间隔时间):
public static void main(String[] args) {
ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);
log.debug("start...");
pool.scheduleAtFixedRate(()->{
log.debug("running...");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}, 1,1, TimeUnit.SECONDS);
}
输出
2022/03/26-22:08:27.038 [main] c.Test2 - start...
2022/03/26-22:08:28.091 [pool-1-thread-1] c.Test2 - running...
2022/03/26-22:08:30.103 [pool-1-thread-1] c.Test2 - running...
2022/03/26-22:08:32.118 [pool-1-thread-1] c.Test2 - running...
2022/03/26-22:08:34.123 [pool-1-thread-1] c.Test2 - running...
分析:一开始,延时1s,接下来,由于任务执行时间>间隔时间,间隔被[撑]到了2s
scheduleWithFixedDelay例子:
public static void main(String[] args) {
ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);
log.debug("start...");
pool.scheduleWithFixedDelay(()->{
log.debug("running...");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}, 1,1, TimeUnit.SECONDS);
}
输出
2022/03/26-22:10:50.281 [main] c.Test3 - start...
2022/03/26-22:10:51.325 [pool-1-thread-1] c.Test3 - running...
2022/03/26-22:10:54.345 [pool-1-thread-1] c.Test3 - running...
2022/03/26-22:10:57.360 [pool-1-thread-1] c.Test3 - running...
2022/03/26-22:11:00.363 [pool-1-thread-1] c.Test3 - running...
分析:一开始,延时1s,scheduleWithFixedDelay的间隔是上一个任务结束 - 延时 - 下一个任务开始
,所以间隔都是3s
评价:整个线程池表现为:线程数固定,任务数多于线程数时,会放入无界队列排队。任务执行完毕,这些线程也不会释放,用来执行延迟或反复处理的任务
9)正确处理执行任务异常
方法1:主动捕捉异常
public static void main(String[] args) throws InterruptedException {
ExecutorService pool = Executors.newFixedThreadPool(1);
pool.submit(() -> {
try {
int i = 1 / 0;
} catch (Exception e) {
e.printStackTrace();
}
});
}
输出
java.lang.ArithmeticException: / by zero
at thread.pool.base.Test3.lambda$main$0(Test3.java:19)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
方法2:使用Future
public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService pool = Executors.newFixedThreadPool(1);
Future<Boolean> future = pool.submit(() -> {
log.debug("task1");
int i = 1 / 0;
return true;
});
log.debug("result:{}", future.get());
}
输出
Exception in thread "main" java.util.concurrent.ExecutionException: java.lang.ArithmeticException: / by zero
at java.util.concurrent.FutureTask.report(FutureTask.java:122)
at java.util.concurrent.FutureTask.get(FutureTask.java:192)
at thread.pool.base.Test4.main(Test4.java:23)
Caused by: java.lang.ArithmeticException: / by zero
at thread.pool.base.Test4.lambda$main$0(Test4.java:20)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
10)Tomcat线程池
Tomcat在哪里用到了线程池呢
- LimitLatch用来限流,可以控制最大连接个数,类似J.U.C中的Semaphore ,后面讲
- Acceptor 只负责 【接收新的Socket连接】
- Poller只负责监听socket channel 是否有【可读I/O事件】
- 一旦可读,封装一个任务对象(socketProcessor),提交给Executor线程池处理
- Executor线程池中的工作线程最终负责【处理请求】
Tomcat线程池扩展了ThreadPoolExecutor,行为稍有不同
- 如果线程总数达到maximumPoolSize
- 这时不会立刻抛RejectExecutionException异常
- 而是再次尝试将任务放入队列,如果还失败,才抛RejectExecutionException异常
源码 tomcat-7.0.42
public void execute(Runnable command, long timeout, TimeUnit unit) {
submittedCount.incrementAndGet();
try {
super.execute(command);
} catch (RejectedExecutionException rx) {
if (super.getQueue() instanceof TaskQueue) {
final TaskQueue queue = (TaskQueue) super.getQueue();
try {
if (!queue.force(command, timeout, unit)) {
submittedCount.decrementAndGet();
throw new RejectedExecutionException("Queue capacity is full.");
}
} catch (InterruptedException x) {
submittedCount.decrementAndGet();
Thread.interrupted();
throw new RejectedExecutionException(x);
}
} else {
submittedCount.decrementAndGet();
throw rx;
}
}
}
TaskQueue.java
public boolean force(Runnable o, long timeout, TimeUnit unit) throws InterruptedException {
if (parent.isShutdown())
throw new RejectedExecutionException(
"Executor not running, can't force a command into the queue"
);
return super.offer(o, timeout, unit); //forces the item onto the queue, to be used if the task is rejected
}
Connector配置
配置项 | 默认值 | 说明 |
---|---|---|
acceptorThreadCount | 1 | acceptor线程数量 |
pollerThreadCount | 1 | poller线程数量 |
minSpareThreads | 10 | 核心线程数,即corePoolSize |
maxThreads | 200 | 最大线程数,即MaximumPoolSize |
executor | - | Executor名称,用来引用下面的Executor |
Executor线程配置
配置项 | 默认值 | 说明 |
---|---|---|
threadPriority | 5 | 线程优先级 |
daemon | true | 是否守护线程 |
minSpareThreads | 25 | 核心线程数,即corePoolSize |
maxThreads | 200 | 最大线程数,即MaximumPoolSize |
maxIdleTime | 60000 | 线程生存时间,单位是毫秒,默认值是1分钟 |
MaxQueueSize | Integer.MAX_VALUE | 队列长度 |
prestartSpareThreads | false | 核心线程是否在服务器启动时启动 |