1 自定义线程池
参考:https://blog.csdn.net/qq_36389060/article/details/121757815
2 ThreadPoolService
2.1 线程池的状态
ThreadPoolExecutor 使用 int 的高 3 位来表示线程池状态,低 29 位表示线程数量
从数字上比较,TERMINATED > TIDYING > STOP > SHUTDOWN > RUNNING,因为是用的int的高3位,最高位为1表示负数
为什么不用两个int来分别存储线程状态和线程个数呢
这些信息存储在一个 ** 原子变量
** 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; }
2.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 拒绝策略
说明:救急线程 = maximumPoolSize - corePoolSize ,每个线程是用到了才创建,节省资源,懒汉式,当阻塞队列达到容量时,还有任务加入就会创建救急线程,它有生存时间。
线程池执行流程
-
线程池中刚开始没有线程,当一个任务提交给线程池后,线程池会创建一个新线程来执行任务。
-
当线程数达到 corePoolSize 并没有线程空闲,这时再加入任务,新加的任务会被加入workQueue 队列排队,直到有空闲的线程。
-
如果队列选择了有界队列,那么任务超过了队列大小时,会创建 maximumPoolSize - corePoolSize 数目的线程来救急。
-
如果线程到达 maximumPoolSize 仍然有新任务这时会执行拒绝策略。拒绝策略 jdk 提供了 4 种实现,其它著名框架也提供了实现
- AbortPolicy 让调用者抛出 RejectedExecutionException 异常,这是默认策略
- CallerRunsPolicy 让调用者运行任务
- DiscardPolicy 放弃本次任务
- DiscardOldestPolicy 放弃队列中最早的任务,本任务取而代之
-
当高峰过去后,超过corePoolSize 的救急线程如果一段时间没有任务做,需要结束节省资源,这个时间由keepAliveTime 和 unit 来控制。
其它框架的拒绝策略
- Dubbo 的实现,在抛出 RejectedExecutionException 异常之前会记录日志,并 dump 线程栈信息,方便定位问题
- Netty 的实现,是创建一个新线程来执行任务
- ActiveMQ 的实现,带超时等待(60s)尝试放入队列,类似我们之前自定义的拒绝策略
- PinPoint 的实现,它使用了一个拒绝策略链,会逐一尝试策略链中每种拒绝策略
2.2.1 newFixedThreadPool
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
- 核心线程数 == 最大线程数(没有救急线程被创建),因此也无需超时时间
- 阻塞队列是无界的,可以放任意数量的任务
评价:适用于任务量已知,相对耗时的任务
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(r,"mypool+t"+t.getAndIncrement());
}
}
);
pool.execute(() -> {
log.debug("1");
});
pool.execute(() -> {
log.debug("2");
});
}
2.2.2 newCachedThreadPool
public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>(),
threadFactory);
}
- 核心线程数是 0, 最大线程数是 Integer.MAX_VALUE,救急线程的空闲生存时间是 60s,意味着
- 全部都是救急线程(60s 后可以回收)
- 救急线程可以无限创建
- 队列采用了 SynchronousQueue 实现特点是,它没有容量,但是当一个线程想放任务,但没有线程来取,放任务的线程是放不进去任务的(一手交钱、一手交货)
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();
sleep(1);
new Thread(() -> {
try {
log.debug("taking {}", 1);
integers.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
},"t2").start();
sleep(1);
new Thread(() -> {
try {
log.debug("taking {}", 2);
integers.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
},"t3").start();
}
- 可以看到,只有当一线程来取任务的时候,该队列才会把任务加入队列
10:18:25.056 [t1] DEBUG pool - putting 1
10:18:25.058 [t2] DEBUG pool - taking 1
10:18:25.059 [t3] DEBUG pool - taking 2
10:18:25.059 [t1] DEBUG pool - 1 putted...
10:18:25.059 [t1] DEBUG pool - putting...2
10:18:25.059 [t1] DEBUG pool - 2 putted...
评价 整个线程池表现为线程数会根据任务量不断增长,没有上限,当任务执行完毕,空闲 1分钟后释放线程。 适合任务数比较密集,但每个任务执行时间较短的情况
2.2.3 newSingleThreadExecutor
public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory) {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(),
threadFactory));
}
使用场景:希望多个任务排队执行。线程数固定为 1,任务数多于 1 时,会放入无界队列排队。任务执行完毕,这唯一的线程也不会被释放。
那么我们自己定义一个线程不行吗,是有区别的
- 自己创建一个单线程串行执行任务,如果任务执行失败而终止那么没有任何补救措施,
而线程池还会新建一个线程,保证池的正常工作
- Executors.newSingleThreadExecutor() 线程个数始终为1,不能修改
- FinalizableDelegatedExecutorService 应用的是装饰器模式,只对外暴露了 ExecutorService 接口,因此不能调用 ThreadPoolExecutor 中特有的方法
- Executors.newFixedThreadPool(1) 初始时为1,以后还可以修改
- 对外暴露的是 ThreadPoolExecutor 对象,可以强转后调用 setCorePoolSize 等方法进行修改
2.3 提交任务
// 执行任务
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;
2.6.1 代码示例 - submit
submit配合Callable带有返回结果
ExecutorService pool1 = Executors.newFixedThreadPool(2);
Future<String> future = pool1.submit(new Callable<String>() {
@Override
public String call() throws Exception {
log.debug("running");
Thread.sleep(1000);
return "ok";
}
});
log.debug("{}",future.get());
2.6.2 代码示例 - invokeAll
invokeAll
List<Future<String>> futures = pool1.invokeAll(Arrays.asList(
() -> {
log.debug("begin...");
Thread.sleep(1000);
return "1";
},
() -> {
log.debug("begin...");
Thread.sleep(500);
return "2";
},
() -> {
log.debug("begin...");
Thread.sleep(2000);
return "2";
}
));
futures.forEach(f -> {
try {
log.debug("{}",f.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
});
2.6.2 代码示例 - invokeAny
invokeAny,找到最先执行完的任务,并返回结果,其它任务取消
String any = pool1.invokeAny(Arrays.asList(
() -> {
log.debug("begin...");
Thread.sleep(1000);
return "1";
},
() -> {
log.debug("begin...");
Thread.sleep(500);
return "2";
},
() -> {
log.debug("begin...");
Thread.sleep(2000);
return "2";
}
));
log.debug("{}",any);
2.4 关闭线程池
2.4.1 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();
}
2.4.2 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;
}
2.4.3 其它方法
// 不在 RUNNING 状态的线程池,此方法就返回 true
boolean isShutdown();
// 线程池状态是否是 TERMINATED
boolean isTerminated();
// 调用 shutdown 后,由于调用线程并不会等待所有任务运行结束,因此如果它想在线程池 TERMINATED 后做些事
情,可以利用此方法等待
boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException;
2.4.4 代码示例
shutdown不会影响正在执行的线程和在任务队列中的线程,并且shutdown不会影响主线程其它代码的执行
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(2);
Future<Integer> future1 = pool.submit(() -> {
log.debug("running...");
Thread.sleep(1000);
log.debug("finish...");
return 1;
});
Future<Integer> future2 = pool.submit(() -> {
log.debug("running...");
Thread.sleep(1000);
log.debug("finish...");
return 2;
});
Future<Integer> future3 = pool.submit(() -> {
log.debug("running...");
Thread.sleep(1000);
log.debug("finish...");
return 3;
});
log.debug("shutdown");
pool.shutdown();
}
11:11:10.092 [main] DEBUG test - shutdown
11:11:10.092 [pool-1-thread-2] DEBUG test - running...
11:11:10.092 [pool-1-thread-1] DEBUG test - running...
11:11:11.097 [pool-1-thread-1] DEBUG test - finish...
11:11:11.097 [pool-1-thread-2] DEBUG test - finish...
11:11:11.097 [pool-1-thread-2] DEBUG test - running...
11:11:12.097 [pool-1-thread-2] DEBUG test - finish...
Process finished with exit code 0
2.5 模式之 Worker Thread
2.6 任务调度线程池 - newScheduledThreadPool
在『任务调度线程池』功能加入之前,可以使用 java.util.Timer 来实现定时功能,Timer 的优点在于简单易用,但
由于所有任务都是由同一个线程来调度,因此所有任务都是串行执行的,同一时间只能有一个任务在执行,前一个
任务的延迟或异常都将会影响到之后的任
Timer中只有一个线程,只能串行执行
Timer timer = new Timer();
TimerTask task1 = new TimerTask() {
@Override
public void run() {
log.debug("task 1");
try {
sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// System.out.println(1/0);
}
};
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);
使用 ScheduledExecutorService 改写
public static void main(String[] args) {
ScheduledExecutorService pool = Executors.newScheduledThreadPool(2);
pool.schedule(
() -> {
log.debug("11111");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}, 0 , TimeUnit.SECONDS);
pool.schedule(
() -> {
log.debug("22222");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}, 1 , TimeUnit.SECONDS);
}
- 可以看到隔了一秒就执行了
08:20:37.548 [pool-1-thread-1] DEBUG test - 11111
08:20:38.557 [pool-1-thread-2] DEBUG test - 22222
测试ScheduledExecutorService 异常处理
public static void main(String[] args) {
ScheduledExecutorService pool = Executors.newScheduledThreadPool(2);
pool.schedule(
() -> {
log.debug("11111");
int i = 2 / 0;
}, 0 , TimeUnit.SECONDS);
pool.schedule(
() -> {
log.debug("22222");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}, 1 , TimeUnit.SECONDS);
}
- 未打印异常,不影响第二个任务的执行,,如果想打印错误信息可以自己用 try/catch
08:21:53.247 [pool-1-thread-1] DEBUG test - 11111
08:21:54.245 [pool-1-thread-2] DEBUG test - 22222
应用:每隔一秒执行 - scheduleAtFixedRate
ScheduledExecutorService pool = Executors.newScheduledThreadPool(2);
pool.scheduleAtFixedRate(
() -> {
log.debug("1111");
},1,1,TimeUnit.SECONDS
);
scheduleWithFixedDelay,定义每个任务之间的时间间隔
pool.scheduleWithFixedDelay(
() -> {
log.debug("1111");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
},1,1,TimeUnit.SECONDS
);
2.7 如何捕获线程池的异常信息
线程池是不会打印异常信息的
主动处理 ==> 自己加try/catch块
被动处理 ==> 使用Callable返回值捕获异常信息
ExecutorService pool = Executors.newFixedThreadPool(2);
Future<Boolean> future = pool.submit(
() -> {
log.debug("111111");
int i = 2 / 0;
return true;
}
);
log.debug("返回结果: {}",future.get());
2.8 应用之定时任务
每周四 18:00 定时执行任务
public static void main(String[] args) {
// 获取当前时间
LocalDateTime now = LocalDateTime.now();
System.out.println(now);
// 获取周四时间
LocalDateTime time = now.withHour(18).withMinute(0).withSecond(0).withNano(0).with(DayOfWeek.THURSDAY);
System.out.println(time);
// 如果当前时间大于本周周四,那么就需要找到下周的周四
if (now.compareTo(time) > 0) {
time = time.plusWeeks(1);
}
System.out.println(time);
long initialDelay = Duration.between(now,time).toMillis();
System.out.println(initialDelay);
// 间隔一周
int period = 1000 * 60 * 24 * 7;
ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);
// 每周四执行
pool.scheduleAtFixedRate(
() -> {
System.out.println("running...");
},initialDelay,period, TimeUnit.MILLISECONDS);
}
2.9 Tomcat线程池
3 Fork/Join线程池
3.1 概念
- Fork/Join 是 JDK 1.7 加入的新的线程池实现,它体现的是一种分治思想,适用于能够进行任务拆分的 cpu 密集型
运算 - 所谓的任务拆分,是将一个大任务拆分为算法上相同的小任务,直至不能拆分可以直接求解。跟递归相关的一些计
算,如归并排序、斐波那契数列、都可以用分治思想进行求解 - Fork/Join 在分治的基础上加入了多线程,可以把每个任务的分解和合并交给不同的线程来完成,进一步提升了运
算效率 - Fork/Join 默认会创建与 cpu 核心数大小相同的线程池
3.2 使用
使用步骤
- 创建任务对象,提交给 Fork/Join 线程池的任务需要继承 RecursiveTask(有返回值)或 RecursiveAction(没有返回值),例如下面定义了一个对 1~n 之间的整数求和的任务
- 然后将任务对象提交给 ForkJoinPool 来执行
public class Test5 {
public static void main(String[] args) {
ForkJoinPool pool = new ForkJoinPool(4);
System.out.println(pool.invoke(new MyTask(5)));
}
}
// 1 ~ n 之间的整数和
@Slf4j(topic = "myTask")
class MyTask extends RecursiveTask<Integer> {
private int n;
public MyTask(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)
MyTask t1 = new MyTask(n - 1);
t1.fork();
log.debug("fork() {} + {}", n, t1);
// 合并(join)结果
int result = n + t1.join();
log.debug("join() {} + {} = {}", n, t1, result);
return result;
}
}
09:32:28.584 [ForkJoinPool-1-worker-2] DEBUG myTask - fork() 4 + {
3}
09:32:28.584 [ForkJoinPool-1-worker-1] DEBUG myTask - fork() 5 + {
4}
09:32:28.584 [ForkJoinPool-1-worker-0] DEBUG myTask - fork() 2 + {
1}
09:32:28.584 [ForkJoinPool-1-worker-3] DEBUG myTask - fork() 3 + {
2}
09:32:28.587 [ForkJoinPool-1-worker-0] DEBUG myTask - join() 1
09:32:28.587 [ForkJoinPool-1-worker-0] DEBUG myTask - join() 2 + {
1} = 3
09:32:28.587 [ForkJoinPool-1-worker-3] DEBUG myTask - join() 3 + {
2} = 6
09:32:28.587 [ForkJoinPool-1-worker-2] DEBUG myTask - join() 4 + {
3} = 10
09:32:28.587 [ForkJoinPool-1-worker-1] DEBUG myTask - join() 5 + {
4} = 15
3.3 优化
- 减少3.2中任务之间的依赖
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;
}
}