提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
前言
上一章我们介绍了如何手写一个线程池,本章我们介绍一下,JDK为我们提供的线程池的实现技术
ThreadPoolExecutor
线程池状态
ThreadPoolExecutor 使用 int 的高 3 位来表示线程池状态,低 29 位表示线程数量
从数字上比较,TERMINATED > TIDYING > STOP > SHUTDOWN > RUNNING
这些信息存储在一个原子变量 ctl 中,目的是将线程池状态与线程个数合二为一,这样就可以用一次 cas 原子操作进行赋值
// c 为旧值, ctlOf 返回结果为新值
ctl.compareAndSet(c, ctlOf(targetState, workerCountOf(c))));
// rs 为高 3 位代表线程池状态, wc 为低 29 位代表线程个数,ctl 是合并它们
private static int ctlOf(int rs, int wc) { return rs | wc; }
构造方法
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler)
- corePoolSize:核心线程数 (最多保留的线程数)
- maximumPoolSize:最大线程数
- keepAliveTime:生存时间 - 针对救急线程
- unit : 时间单位- 针对救急线程
- workQueue:阻塞队列
- threadFactory:线程工厂 - 可以为线程创建时起个好名字
- handler:拒绝策略
请务必熟记7个参数,以及所代表的含义
工作方式:
-
线程池中刚开始没有线程,当一个任务提交给线程池后,线程池会创建一个新线程来执行任务
-
当线程数达到 corePoolSize 并没有线程空闲,这时再加入任务,新加的任务会被加入workQueue 队列排队,直到有空闲的线程。
-
如果队列选择了有界队列,那么任务超过了队列大小时,会创建 maximumPoolSize - corePoolSize 数目的线程来救急。
-
如果线程到达 maximumPoolSize 仍然有新任务这时会执行拒绝策略。拒绝策略 jdk 提供了 4 种实现,其它著名框架也提供了实现
AbortPolicy 让调用者抛出 RejectedExecutionException 异常,这是默认策略
CallerRunsPolicy 让调用者运行任务
DiscardPolicy 放弃本次任务
DiscardOldestPolicy 放弃队列中最早的任务,本任务取而代之
Dubbo 的实现,在抛出 RejectedExecutionException 异常之前会记录日志,并 dump 线程栈信息,方便定位问题
Netty 的实现,是创建一个新线程来执行任务
ActiveMQ 的实现,带超时等待(60s)尝试放入队列,类似我们之前自定义的拒绝策略
PinPoint 的实现,它使用了一个拒绝策略链,会逐一尝试策略链中每种拒绝策略 -
当高峰过去后,超过corePoolSize 的救急线程如果一段时间没有任务做,需要结束节省资源,这个时间由keepAliveTime 和 unit 来控制。
-
JDK提供的拒绝策略:
根据这个构造方法,JDK Executors 类中提供了众多工厂方法来创建各种用途的线程池
newFixedThreadPool
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
特点:
- 核心线程数 == 最大线程数(没有救急线程被创建),因此也无需超时时间
- 阻塞队列是无界的,可以放任意数量的任务
适用于任务量已知,相对耗时的任务
@Slf4j(topic = "c.TestThreadPoolExcutors")
public class TestThreadPoolExcutors {
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(2);
pool.execute(()->{
log.debug("1");
});
pool.execute(()->{
log.debug("2");
});
pool.execute(()->{
log.debug("3");
});
}
}
11:38:48.399 [pool-1-thread-1] DEBUG c.TestThreadPoolExcutors - 1
11:38:48.399 [pool-1-thread-2] DEBUG c.TestThreadPoolExcutors - 2
11:38:48.405 [pool-1-thread-1] DEBUG c.TestThreadPoolExcutors - 3
注意核心线程运行完成后,并没有主动结束
我们看下这个方法
1、线程工厂
可以看到我们创建的newFixedThreadPool线程池使用了默认的线程工厂,和默认的拒绝策略
其实线程工厂主要作用就是给线程起个好听点的名字,我们也可以自己实现线程工厂
public class TestThreadPoolExcutors {
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(2, new ThreadFactory() {
private AtomicInteger t = new AtomicInteger(1);
@Override
public Thread newThread(Runnable r) {
return new Thread("mypool_t"+t.getAndIncrement());
}
});
pool.execute(()->{
log.debug("1");
});
pool.execute(()->{
log.debug("2");
});
pool.execute(()->{
log.debug("3");
});
}
}
2、newFixedThreadPool采用的是默认的拒绝策略,就是抛出异常
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 实现特点是,它没有容量,没有线程来取是放不进去的(一手交钱、一手交货)
@Slf4j(topic = "c.TestThreadPoolExcutors")
public class TestSychronizedQueue {
public static void main(String[] args) throws InterruptedException {
SynchronousQueue<Integer> integers = new SynchronousQueue<>();
new Thread(() -> {
try {
log.debug("putting {} ", 1);
integers.put(1);
log.debug("{} putted...", 1);
log.debug("putting...{} ", 2);
integers.put(2);
log.debug("{} putted...", 2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "t1").start();
Thread.sleep(1000);
new Thread(() -> {
try {
log.debug("taking {}", 1);
integers.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "t2").start();
Thread.sleep(1000);
new Thread(() -> {
try {
log.debug("taking {}", 2);
integers.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "t3").start();
}
}
11:55:40.771 [t1] DEBUG c.TestThreadPoolExcutors - putting 1
11:55:41.779 [t2] DEBUG c.TestThreadPoolExcutors - taking 1
11:55:41.779 [t1] DEBUG c.TestThreadPoolExcutors - 1 putted...
11:55:41.779 [t1] DEBUG c.TestThreadPoolExcutors - putting...2
11:55:42.792 [t3] DEBUG c.TestThreadPoolExcutors - taking 2
11:55:42.793 [t1] DEBUG c.TestThreadPoolExcutors - 2 putted...
整个线程池表现为线程数会根据任务量不断增长,没有上限,当任务执行完毕,空闲 1分钟后释放线程。 适合任务数比较密集,但每个任务执行时间较短的情况
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 等方法进行修改
private static void test02(){
ExecutorService pool = Executors.newSingleThreadExecutor();
pool.execute(()->{
log.debug("1");
int i = 1/0;
});
pool.execute(()->{
log.debug("2");
});
pool.execute(()->{
log.debug("3");
});
12:02:22.893 [pool-1-thread-1] DEBUG c.TestThreadPoolExcutors - 1
Exception in thread "pool-1-thread-1" java.lang.ArithmeticException: / by zero
12:02:22.900 [pool-1-thread-2] DEBUG c.TestThreadPoolExcutors - 2
at cn.itcast.text.TestThreadPoolExcutors.lambda$test02$3(TestThreadPoolExcutors.java:41)
12:02:22.900 [pool-1-thread-2] DEBUG c.TestThreadPoolExcutors - 3
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)
看一下FinalizableDelegatedExecutorService
static class FinalizableDelegatedExecutorService
extends DelegatedExecutorService {
FinalizableDelegatedExecutorService(ExecutorService executor) {
super(executor);
}
protected void finalize() {
super.shutdown();
}
}
FinalizableDelegatedExecutorService继承了DelegatedExecutorService
看下DelegatedExecutorService:
static class DelegatedExecutorService extends AbstractExecutorService {
private final ExecutorService e;
DelegatedExecutorService(ExecutorService executor) { e = executor; }
public void execute(Runnable command) { e.execute(command); }
public void shutdown() { e.shutdown(); }
public List<Runnable> shutdownNow() { return e.shutdownNow(); }
public boolean isShutdown() { return e.isShutdown(); }
public boolean isTerminated() { return e.isTerminated(); }
public boolean awaitTermination(long timeout, TimeUnit unit)
throws InterruptedException {
return e.awaitTermination(timeout, unit);
}
public Future<?> submit(Runnable task) {
return e.submit(task);
}
public <T> Future<T> submit(Callable<T> task) {
return e.submit(task);
}
public <T> Future<T> submit(Runnable task, T result) {
return e.submit(task, result);
}
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
throws InterruptedException {
return e.invokeAll(tasks);
}
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
long timeout, TimeUnit unit)
throws InterruptedException {
return e.invokeAll(tasks, timeout, unit);
}
public <T> T invokeAny(Collection<? extends Callable<T>> tasks)
throws InterruptedException, ExecutionException {
return e.invokeAny(tasks);
}
public <T> T invokeAny(Collection<? extends Callable<T>> tasks,
long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
return e.invokeAny(tasks, timeout, unit);
}
}
ExecutorService e是通过构造器传进去的,DelegatedExecutorService 方法都是通过e间接调用的
提交任务
前面我们的任务提交方法,使用都是execute,下面我们介绍一下其他的提交方法:
// 执行任务
void execute(Runnable command);
// 提交任务 task,用返回值 Future 获得任务执行结果
<T> Future<T> submit(Callable<T> task);
// 提交 tasks 中所有任务
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
throws InterruptedException;
// 提交 tasks 中所有任务,带超时时间
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
long timeout, TimeUnit unit)throws InterruptedException;
// 提交 tasks 中所有任务,哪个任务先成功执行完毕,返回此任务执行结果,其它任务取消
<T> T invokeAny(Collection<? extends Callable<T>> tasks)
throws InterruptedException, ExecutionException;
// 提交 tasks 中所有任务,哪个任务先成功执行完毕,返回此任务执行结果,其它任务取消,带超时时间
<T> T invokeAny(Collection<? extends Callable<T>> tasks,long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
execute:我们就不再介绍了,前面已经演示了,注意里面传入的任务是没有返回值的Runnable。
Future submit(Callable task):它是有返回值的提交方法,Callable与Runnable的区别是Callable有返回值,返回值用Future接,底层用的是我们之前说过的保护性暂停模式
@Slf4j(topic = "c.testSubmit")
public class testSubmit {
public static void main(String[] args) throws Exception{
ExecutorService pool = Executors.newFixedThreadPool(2);
Future<String> future = pool.submit(new Callable<String>() {
@Override
public String call() throws Exception {
log.debug("running");
Thread.sleep(1000);
return "ok";
}
});
log.debug("{}",future.get());
}
}
12:27:49.203 [pool-1-thread-1] DEBUG c.testSubmit - running
12:27:50.231 [main] DEBUG c.testSubmit - ok
invokeAll:
@Slf4j(topic = "c.testSubmit")
public class testSubmit {
public static void main(String[] args) throws Exception {
ExecutorService pool = Executors.newFixedThreadPool(2);
List<Future<Object>> futures = pool.invokeAll(Arrays.asList(
() -> {
log.debug("begin");
Thread.sleep(1000);
return "1";
},
() -> {
log.debug("begin");
Thread.sleep(500);
return "2";
},
() -> {
log.debug("begin");
Thread.sleep(1500);
return "3";
}
));
futures.forEach(f->{
try {
log.debug("{}",f.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
});
}
}
12:36:12.942 [pool-1-thread-1] DEBUG c.testSubmit - begin
12:36:12.942 [pool-1-thread-2] DEBUG c.testSubmit - begin
12:36:13.455 [pool-1-thread-2] DEBUG c.testSubmit - begin
12:36:15.069 [main] DEBUG c.testSubmit - 1
12:36:15.072 [main] DEBUG c.testSubmit - 2
12:36:15.072 [main] DEBUG c.testSubmit - 3
invokeAny:
@Slf4j(topic = "c.testSubmit")
public class testSubmit {
public static void main(String[] args) throws Exception {
ExecutorService pool = Executors.newFixedThreadPool(2);
String o = pool.invokeAny(Arrays.asList(
() -> {
log.debug("begin");
Thread.sleep(1000);
return "1";
},
() -> {
log.debug("begin");
Thread.sleep(500);
return "2";
},
() -> {
log.debug("begin");
Thread.sleep(1500);
return "3";
}
));
System.out.println(o);
}
}
12:38:33.437 [pool-1-thread-2] DEBUG c.testSubmit - begin
12:38:33.437 [pool-1-thread-1] DEBUG c.testSubmit - begin
2
12:38:33.954 [pool-1-thread-2] DEBUG c.testSubmit - begin
关闭线程池
- shutdown
/*
线程池状态变为 SHUTDOWN
- 不会接收新任务
- 但已提交任务会执行完
- 此方法不会阻塞调用线程的执行
*/
void shutdown();
源码:
public void shutdown() {
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
checkShutdownAccess();
// 修改线程池状态
advanceRunState(SHUTDOWN);
// 仅会打断空闲线程
interruptIdleWorkers();
onShutdown(); // 扩展点 ScheduledThreadPoolExecutor
} finally {
mainLock.unlock();
}
// 尝试终结(没有运行的线程可以立刻终结,如果还有运行的线程也不会等)
tryTerminate();
}
@Slf4j(topic = "c.TestShutDown")
public class TestShutDown {
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(2);
pool.submit(()->{
log.debug("task 1 running");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
log.debug("task 1 finish");
});
pool.submit(()->{
log.debug("task 2 running");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
log.debug("task 2 finish");
});
pool.submit(()->{
log.debug("task 3 running");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
log.debug("task 3 finish");
});
log.debug("shutdown");
pool.shutdown();
log.debug("other");
}
}
12:53:45.847 [main] DEBUG c.TestShutDown - shutdown
12:53:45.853 [main] DEBUG c.TestShutDown - other
12:53:45.856 [pool-1-thread-1] DEBUG c.TestShutDown - task 1 running
12:53:45.856 [pool-1-thread-2] DEBUG c.TestShutDown - task 2 running
12:53:46.859 [pool-1-thread-1] DEBUG c.TestShutDown - task 1 finish
12:53:46.859 [pool-1-thread-2] DEBUG c.TestShutDown - task 2 finish
12:53:46.860 [pool-1-thread-1] DEBUG c.TestShutDown - task 3 running
12:53:47.861 [pool-1-thread-1] DEBUG c.TestShutDown - task 3 finish
核心线程是2个,任务是3个,调用shutdown,并不会关闭正在执行的任务,和队列中阻塞的任务。
shutdown()调用后,不会阻塞其他代码的执行
- shutdownNow
/*
线程池状态变为 STOP
- 不会接收新任务
- 会将队列中的任务返回
- 并用 interrupt 的方式中断正在执行的任务
*/
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;
}
Slf4j(topic = "c.shutdownNow")
public class TestShutDown {
public static void main(String[] args) throws InterruptedException {
ExecutorService pool = Executors.newFixedThreadPool(2);
pool.submit(()->{
log.debug("task 1 running");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
log.debug("task 1 finish");
});
pool.submit(()->{
log.debug("task 2 running");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
log.debug("task 2 finish");
});
pool.submit(()->{
log.debug("task 3 running");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
log.debug("task 3 finish");
});
log.debug("shutdown");
List<Runnable> runnables = pool.shutdownNow();
log.debug("{}",runnables);
}
}
12:56:57.995 [main] DEBUG c.TestShutDown - shutdown
12:56:58.001 [main] DEBUG c.TestShutDown - [java.util.concurrent.FutureTask@3581c5f3]
12:56:58.018 [pool-1-thread-1] DEBUG c.TestShutDown - task 1 running
12:56:58.020 [pool-1-thread-2] DEBUG c.TestShutDown - task 2 running
12:56:58.020 [pool-1-thread-1] DEBUG c.TestShutDown - task 1 finish
12:56:58.020 [pool-1-thread-2] DEBUG c.TestShutDown - task 2 finish
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at cn.itcast.text.TestShutDown.lambda$main$0(TestShutDown.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)
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at cn.itcast.text.TestShutDown.lambda$main$1(TestShutDown.java:29)
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)
shutdownNow的返回结果是队列中还未执行的任务,你可以对这部分任务做处理
因为我们的任务都是sleep。抛出sleep interrupted,说明shutdownNow底层是interrupt方法。
- 其它方法
// 不在 RUNNING 状态的线程池,此方法就返回 true
boolean isShutdown();
// 线程池状态是否是 TERMINATED
boolean isTerminated();
// 调用 shutdown 后,由于调用线程并不会等待所有任务运行结束,因此如果它想在线程池 TERMINATED 后做些事
情,可以利用此方法等待
boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException;
异步模式之工作线程
定义
让有限的工作线程(Work Thread)来轮流异步处理无限多的任务。也可以将其归为分工模式,它的典型实现就是线程池,也体现了经典设计模式中的享元模式
例如,海底捞的服务员(线程)来轮流处每位客人的点餐(任务),如果为每位客人都配一位专属的服务员,那么成本就太高了(对比另一种设计模式:Thread-Per-Message)
注意,不同任务类型应该使用不同的线程池,这样能够避免饥饿,并提高效率
例如,如果一个餐馆的的工人既要招呼客人(任务类型A),又要到后厨做菜(任务类型B)显然效率不咋地,分为服务员(线程池A)和厨师(线程池B)更为合理,当然你能想到更细致的分工
饥饿
固定大小线程池会有饥饿现象:
- 两个工人是同一个线程池中的两个线程
- 他们要做的事是:为客人点餐和都后厨做菜,这是两个阶段的工作
客人点餐:必须先点完餐,等菜做好,上菜,在次期间处理点餐的工人必须等待
后厨做菜:就是做菜 - 比如工人A处理了点餐任务,接下来他要等待工人B把菜做好,然后上菜,他俩也配合蛮好
- 但是现在同时来了两个客人,这个时候工人A和工人B都去处理点餐了,就没人做饭了,就发生了饥饿
注意这个饥饿是指线程数量不足导致的饥饿
模拟
@Slf4j(topic = "c.TestStarvation")
public class TestStarvation {
static final List<String> MENU = Arrays.asList("地三鲜","宫保鸡丁","辣子鸡丁","烤鸡翅");
static Random random = new Random();
static String cooking(){
return MENU.get(random.nextInt(MENU.size()));
}
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(2);
pool.execute(()->{
log.debug("处理点餐");
Future<String> future = pool.submit(() -> {
log.debug("做菜");
return cooking();
});
try {
log.debug("上菜{}",future.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
});
}
}
上面相当于是店里两个工作人员(核心线程),来了一个客人(任务),一个线程取处理点餐,同时让另外一个人做菜,点餐的人要等待做菜的人做好菜,然后上菜。
14:45:38.646 [pool-1-thread-1] DEBUG c.TestStarvation - 处理点餐
14:45:38.665 [pool-1-thread-2] DEBUG c.TestStarvation - 做菜
14:45:38.666 [pool-1-thread-1] DEBUG c.TestStarvation - 上菜烤鸡翅
那如果店里来了两个客人呢(两任务)
@Slf4j(topic = "c.TestStarvation")
public class TestStarvation {
static final List<String> MENU = Arrays.asList("地三鲜","宫保鸡丁","辣子鸡丁","烤鸡翅");
static Random random = new Random();
static String cooking(){
return MENU.get(random.nextInt(MENU.size()));
}
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(2);
pool.execute(()->{
log.debug("处理点餐");
Future<String> future = pool.submit(() -> {
log.debug("做菜");
return cooking();
});
try {
log.debug("上菜{}",future.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
});
pool.execute(()->{
log.debug("处理点餐");
Future<String> future = pool.submit(() -> {
log.debug("做菜");
return cooking();
});
try {
log.debug("上菜{}",future.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
});
}
}
14:50:21.019 [pool-1-thread-1] DEBUG c.TestStarvation - 处理点餐
14:50:21.019 [pool-1-thread-2] DEBUG c.TestStarvation - 处理点餐
两个工作人员(核心线程)都去点餐了,没有人做菜,而这个人都要等待其他线程做菜,但是已经没有其他线程了,于是两个线程都阻塞在future.get()。
注意这里阻塞不是死锁,用jconsole检测一下,并没有发现死锁
这就是由于线程数不足导致的阻塞,是一种饥饿问题
解决
解决上述的饥饿问题,有一种很简单粗暴的方式,就是再招聘一个店员
ExecutorService pool = Executors.newFixedThreadPool(3);
14:55:52.623 [pool-1-thread-1] DEBUG c.TestStarvation - 处理点餐
14:55:52.619 [pool-1-thread-2] DEBUG c.TestStarvation - 处理点餐
14:55:52.642 [pool-1-thread-3] DEBUG c.TestStarvation - 做菜
14:55:52.643 [pool-1-thread-2] DEBUG c.TestStarvation - 上菜烤鸡翅
14:55:52.648 [pool-1-thread-2] DEBUG c.TestStarvation - 做菜
14:55:52.648 [pool-1-thread-1] DEBUG c.TestStarvation - 上菜地三鲜
但是总不能每次来一个客人,招聘一个店员吧,而饥饿的原因是因为,员工分工不明确,我们应该让不同的工作交给不同的员工做(不同任务类型应该使用不同的线程池,点餐和上菜是一个任务,做菜是另外一个任务)
于是我们上述逻辑修改代码
@Slf4j(topic = "c.TestStarvation")
public class TestStarvation {
static final List<String> MENU = Arrays.asList("地三鲜","宫保鸡丁","辣子鸡丁","烤鸡翅");
static Random random = new Random();
static String cooking(){
return MENU.get(random.nextInt(MENU.size()));
}
public static void main(String[] args) {
ExecutorService waiterPool = Executors.newFixedThreadPool(1);
ExecutorService cookPool = Executors.newFixedThreadPool(1);
waiterPool.execute(()->{
log.debug("处理点餐");
Future<String> future = cookPool.submit(() -> {
log.debug("做菜");
return cooking();
});
try {
log.debug("上菜{}",future.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
});
waiterPool.execute(()->{
log.debug("处理点餐");
Future<String> future = cookPool.submit(() -> {
log.debug("做菜");
return cooking();
});
try {
log.debug("上菜{}",future.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
});
}
}
创建了两个线程池waiterPool ,cookPool 线程数都是1,分别戴代表一个专门点餐和上菜的工作人员,一个专门做菜的工作人员,由下面测试结果,也能看出
15:01:23.754 [pool-1-thread-1] DEBUG c.TestStarvation - 处理点餐
15:01:23.763 [pool-2-thread-1] DEBUG c.TestStarvation - 做菜
15:01:23.764 [pool-1-thread-1] DEBUG c.TestStarvation - 上菜地三鲜
15:01:23.766 [pool-1-thread-1] DEBUG c.TestStarvation - 处理点餐
15:01:23.767 [pool-2-thread-1] DEBUG c.TestStarvation - 做菜
15:01:23.767 [pool-1-thread-1] DEBUG c.TestStarvation - 上菜宫保鸡丁
创建多少线程合适呢
- 过小会导致程序不能充分利用系统资源,容易导致饥饿
- 过大会导致频繁的上下文切换,占用更多内存
CPU密集型运算
IO密集型运算
任务调度线程池
过时的timer
在『任务调度线程池』功能加入之前,可以使用 java.util.Timer 来实现定时功能,Timer 的优点在于简单易用,但由于所有任务都是由同一个线程来调度,因此所有任务都是串行执行的,同一时间只能有一个任务在执行,前一个任务的延迟或异常都将会影响到之后的任务
@Slf4j(topic = "c.TestTimer")
public class TestTimer {
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 添加两个任务,希望它们都在 1s 后执行
// 但由于 timer 内只有一个线程来顺序执行队列中的任务,因此『任务1』的延时,影响了『任务2』的执行
timer.schedule(task1, 1000);
timer.schedule(task2, 1000);
}
}
15:12:32.837 [Timer-0] DEBUG c.TestTimer - task 1
15:12:34.857 [Timer-0] DEBUG c.TestTimer - task 2
注意如果任务1执行报错,会直接导致任务2无法执行,Timer了解即可,已经过时了。
ScheduledExecutorService
延时执行 schedule
@Slf4j(topic = "c.TestTimer")
public class TestTimer {
public static void main(String[] args) {
ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);
// 添加两个任务,希望它们都在 1s 后执行
executor.schedule(() -> {
System.out.println("任务1,执行时间:" + new Date());
Thread.sleep(2000);
int i = 1/0;
}, 1000, TimeUnit.MILLISECONDS);
executor.schedule(() -> {
System.out.println("任务2,执行时间:" + new Date());
}, 1000, TimeUnit.MILLISECONDS);
}
}
任务2,执行时间:Thu May 26 15:32:26 CST 2022
任务1,执行时间:Thu May 26 15:32:26 CST 2022
可以发现这两个任务是异步执行的,而且即使任务1出现了异常,也没有抛出
定时执行 scheduleAtFixedRate
@Slf4j(topic = "c.TestTimer")
public class TestTimer {
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);
}
}
15:36:31.104 [main] DEBUG c.TestTimer - start...
15:36:32.221 [pool-1-thread-1] DEBUG c.TestTimer - running...
15:36:34.236 [pool-1-thread-1] DEBUG c.TestTimer - running...
15:36:36.252 [pool-1-thread-1] DEBUG c.TestTimer - running...
15:36:38.266 [pool-1-thread-1] DEBUG c.TestTimer - running..
...
scheduleAtFixedRate任务的执行时间会覆盖延迟时间,注意和下面的不同
pool.scheduleWithFixedDelay(()->{
log.debug("running...");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
},1,1,TimeUnit.SECONDS);
15:40:20.865 [main] DEBUG c.TestTimer - start...
15:40:21.987 [pool-1-thread-1] DEBUG c.TestTimer - running...
15:40:25.014 [pool-1-thread-1] DEBUG c.TestTimer - running...
15:40:28.043 [pool-1-thread-1] DEBUG c.TestTimer - running...
15:40:31.067 [pool-1-thread-1] DEBUG c.TestTimer - running...
...
处理异常
使用线程池处理任务,如果不对异常做处理,默认是看不出任务执行中的异常的
@Slf4j(topic = "c.TestTimer")
public class TestTimer {
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(1);
pool.submit(()->{
log.debug("task1");
int i = 1/0;
});
}
}
15:45:41.501 [pool-1-thread-1] DEBUG c.TestTimer - task1
我们int i = 1/0;是一定异常的,但是结果中看不出
解决方法1:主动的try catch异常
@Slf4j(topic = "c.TestTimer")
public class TestTimer {
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(1);
pool.submit(()->{
log.debug("task1");
try {
int i = 1/0;
}catch (Exception e){
e.printStackTrace();
}
});
}
}
15:47:09.471 [pool-1-thread-1] DEBUG c.TestTimer - task1
java.lang.ArithmeticException: / by zero
at cn.itcast.text.TestTimer.lambda$main$0(TestTimer.java:20)
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)
解决方法1:使用Callable获取feture
feture不仅可以获取任务的执行结果,如果执行中出现异常,会把异常返回
@Slf4j(topic = "c.TestTimer")
public class TestTimer {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService pool = Executors.newFixedThreadPool(1);
Future<Boolean> future = pool.submit(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
log.debug("task1");
int i = 1 / 0;
return true;
}
});
log.debug("result:{}",future.get());
}
}
15:52:11.602 [pool-1-thread-1] DEBUG c.TestTimer - task1
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 cn.itcast.text.TestTimer.main(TestTimer.java:22)
Caused by: java.lang.ArithmeticException: / by zero
at cn.itcast.text.TestTimer$1.call(TestTimer.java:18)
at cn.itcast.text.TestTimer$1.call(TestTimer.java:14)
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)
Tomcat 线程池
Tomcat 在哪里用到了线程池呢
- LimitLatch 用来限流,可以控制最大连接个数,类似 J.U.C 中的 Semaphore 后面再讲
- Acceptor 只负责【接收新的 socket 连接】
- Poller 只负责监听 socket channel 是否有【可读的 I/O 事件】
- 一旦可读,封装一个任务对象(socketProcessor),提交给 Executor 线程池处理
- Executor 线程池中的工作线程最终负责【处理请求】
Tomcat 线程池扩展了 ThreadPoolExecutor,行为稍有不同
- 如果总线程数达到 maximumPoolSize
这时不会立刻抛 RejectedExecutionException 异常
而是再次尝试将任务放入队列,如果还失败,才抛出 RejectedExecutionException 异常
源码 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 配置
Executor 线程配置
Fork/Join
1 、概念
Fork/Join 是 JDK 1.7 加入的新的线程池实现,它体现的是一种分治思想,适用于能够进行任务拆分的 cpu 密集型运算
所谓的任务拆分,是将一个大任务拆分为算法上相同的小任务,直至不能拆分可以直接求解。跟递归相关的一些计算,如归并排序、斐波那契数列、都可以用分治思想进行求解
Fork/Join 在分治的基础上加入了多线程,可以把每个任务的分解和合并交给不同的线程来完成,进一步提升了运算效率
Fork/Join 默认会创建与 cpu 核心数大小相同的线程池
2、 使用
提交给 Fork/Join 线程池的任务需要继承 RecursiveTask(有返回值)或 RecursiveAction(没有返回值),例如下面定义了一个对 1~n 之间的整数求和的任务
@Slf4j(topic = "c.AddTask")
class AddTask1 extends RecursiveTask<Integer> {
int n;
public AddTask1(int n) {
this.n = n;
}
@Override
public String toString() {
return "{" + n + '}';
}
@Override
protected Integer compute() {
// 如果 n 已经为 1,可以求得结果了
if (n == 1) {
log.debug("join() {}", n);
return n;
}
// 将任务进行拆分(fork)
AddTask1 t1 = new AddTask1(n - 1);
t1.fork();
log.debug("fork() {} + {}", n, t1);
// 合并(join)结果
int result = n + t1.join();
log.debug("join() {} + {} = {}", n, t1, result);
return result;
}
}
然后提交给 ForkJoinPool 来执行
public static void main(String[] args) {
ForkJoinPool pool = new ForkJoinPool(4);
System.out.println(pool.invoke(new AddTask1(5)));
}
结果
[ForkJoinPool-1-worker-0] - fork() 2 + {1}
[ForkJoinPool-1-worker-1] - fork() 5 + {4}
[ForkJoinPool-1-worker-0] - join() 1
[ForkJoinPool-1-worker-0] - join() 2 + {1} = 3
[ForkJoinPool-1-worker-2] - fork() 4 + {3}
[ForkJoinPool-1-worker-3] - fork() 3 + {2}
[ForkJoinPool-1-worker-3] - join() 3 + {2} = 6
[ForkJoinPool-1-worker-2] - join() 4 + {3} = 10
[ForkJoinPool-1-worker-1] - join() 5 + {4} = 15
15
用图来表示
改进
class AddTask3 extends RecursiveTask<Integer> {
int begin;
int end;
public AddTask3(int begin, int end) {
this.begin = begin;
this.end = end;
}
@Override
public String toString() {
return "{" + begin + "," + end + '}';
}
@Override
protected Integer compute() {
// 5, 5
if (begin == end) {
log.debug("join() {}", begin);
return begin;
}
// 4, 5
if (end - begin == 1) {
log.debug("join() {} + {} = {}", begin, end, end + begin);
return end + begin;
}
// 1 5
int mid = (end + begin) / 2; // 3
AddTask3 t1 = new AddTask3(begin, mid); // 1,3
t1.fork();
AddTask3 t2 = new AddTask3(mid + 1, end); // 4,5
t2.fork();
log.debug("fork() {} + {} = ?", t1, t2);
int result = t1.join() + t2.join();
log.debug("join() {} + {} = {}", t1, t2, result);
return result;
}
}
然后提交给 ForkJoinPool 来执行
public static void main(String[] args) {
ForkJoinPool pool = new ForkJoinPool(4);
System.out.println(pool.invoke(new AddTask3(1, 10)));
}
结果
[ForkJoinPool-1-worker-0] - join() 1 + 2 = 3
[ForkJoinPool-1-worker-3] - join() 4 + 5 = 9
[ForkJoinPool-1-worker-0] - join() 3
[ForkJoinPool-1-worker-1] - fork() {1,3} + {4,5} = ?
[ForkJoinPool-1-worker-2] - fork() {1,2} + {3,3} = ?
[ForkJoinPool-1-worker-2] - join() {1,2} + {3,3} = 6
[ForkJoinPool-1-worker-1] - join() {1,3} + {4,5} = 15
15
用图来表示
Fork/Join难就难在怎么拆任务