线程池拒绝策略
- 简介
AbortPolicy:该策略直接抛出异常,阻止系统正常工作
CallerRunsPolicy:只要线程池没有关闭,该策略直接在调用者线程中,执行当前被丢弃的任务
DiscardPolicy:直接把任务丢弃
DiscardOldestPolicy:丢弃最老的一个请求(任务队列里面的第一个),再尝试提交任务
- 查看类结构
# 查看ThreadPoolExecutor类
public static class AbortPolicy implements RejectedExecutionHandler {
/**
* Creates an {@code AbortPolicy}.
*/
public AbortPolicy() { }
/**
* Always throws RejectedExecutionException.
*
* @param r the runnable task requested to be executed
* @param e the executor attempting to execute this task
* @throws RejectedExecutionException always
*/
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
throw new RejectedExecutionException("Task " + r.toString() +
" rejected from " +
e.toString());
}
}
- 自定义线程拒绝策略
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
public class CustomPolicy implements RejectedExecutionHandler {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
// 执行其他操作,例如发送邮件告警
System.out.println("线程池满了");
}
}
# 测试使用
public class ThreadPoolDemo {
public static void main(String[] args) throws ExecutionException, InterruptedException {
// 创建队列,队列大小指定10
LinkedBlockingQueue<Runnable> objects = new LinkedBlockingQueue<>(10);
// 创建线程池,每次处理10个任务,3秒
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10, 20, 3L,
TimeUnit.SECONDS, objects, new CustomPolicy()); // 使用自定义策略
// 初始化核心线程
threadPoolExecutor.prestartAllCoreThreads();
// 执行50个线程
for (int i = 0; i < 50; i++) {
threadPoolExecutor.submit(()->{ // 提交任务
try {
Thread.sleep(2000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(threadPoolExecutor.getActiveCount()); // 获取线程池中活跃的数量
});
}
}
}