回应一下这个篇文章老哥下面的评论。
https://blog.csdn.net/shijianjinghun/article/details/110134275#comments_15100822
因为原文是循环添加的任务,阻塞main线程不太容易发现。所以特地写了以下代码进行验证。
package com.langzi.app.controller;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* @Author LangZi
* @CreateDate 2021/2/22 17:03
* @Motto Goals determines what you are going to be,diligence determines what you are able to be!
* @Description TODO
*/
public class ThreadPoolExecutorDemo {
public static void main(String[] args) {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
1, 2, 30, TimeUnit.SECONDS,
new LinkedBlockingQueue<>(1),
new RejectedExecutionHandler() {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
try {
executor.getQueue().put(r);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
);
// 预期任务1,应该直接执行
threadPoolExecutor.execute(() -> {
System.out.println("任务1执行 : " + Thread.currentThread().getName());
sleepThread();
System.out.println("任务1 : 执行完成");
});
//预期任务2,加入阻塞队列
threadPoolExecutor.execute(() -> {
System.out.println("任务2执行 : " + Thread.currentThread().getName());
sleepThread();
System.out.println("任务2 : 执行完成");
});
//预期任务3,创建“非核心”线程执行
threadPoolExecutor.execute(() -> {
System.out.println("任务3执行 : " + Thread.currentThread().getName());
sleepThread();
System.out.println("任务3 : 执行完成");
});
//预期任务4,会阻塞main线程,直到成功put()到队列中
threadPoolExecutor.execute(() -> {
System.out.println("任务4执行: " + Thread.currentThread().getName());
sleepThread();
System.out.println("任务4 : 执行完成");
});
//预期,如果重写拒绝策略没有阻塞主线程,下面这句应该会直接打印,肯定会在任务1完成前打印
System.out.println("重写拒绝策略没有阻塞主线程???");
//关闭线程池
threadPoolExecutor.shutdown();
}
public static void sleepThread() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
不知道这样写,有没有问题。如有问题,请在评论区指正。
每个线程睡眠了5秒,我觉得够长了。
执行结果: