Python 官方文档:入门教程 => 点击学习
目录线程池ThreadPoolExecutor的拒绝策略AbortPolicy策略线程池ThreadPoolExecutor的拒绝策略 线程池中的线程资源全部被占用时,对新添加的Ta
线程池中的线程资源全部被占用时,对新添加的Task任务有不同的处理策略,在默认的情况下,
ThreadPoolExecutor类中有4种不同的处理方式:
AbortPolicy策略是当任务添加到线程池中被拒绝时,它将抛出RejectedExecutionException异常。
线程执行代码如下:
public class FirstRunnable implements Runnable {
@Override
public void run() {
SimpleDateFORMat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
try {
System.out.println(Thread.currentThread().getName() +" 开始时间:"+simpleDateFormat.format(new Date()));
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName() +" 结束时间:"+simpleDateFormat.format(new Date()));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
运行类代码如下:
public class AbortPolicyRun {
public static void main(String[] args) {
FirstRunnable firstRunnable = new FirstRunnable();
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 3, 5, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(2), new ThreadPoolExecutor.AbortPolicy());
for (int i = 0; i < 7 ; i++) {
threadPoolExecutor.execute(firstRunnable);
}
}
}
运行结果如下:
Exception in thread "main" java.util.concurrent.RejectedExecutionException: Task com.ozx.concurrentprogram.executor.service.FirstRunnable@6c629d6e rejected from java.util.concurrent.ThreadPoolExecutor@5f5a92bb[Running, pool size = 3, active threads = 3, queued tasks = 2, completed tasks = 0]
at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2063)
at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:830)
at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1379)
at com.ozx.concurrentprogram.executor.controller.AbortPolicyRun.main(AbortPolicyRun.java:19)
pool-1-thread-3 开始时间:16:20:27
pool-1-thread-1 开始时间:16:20:27
pool-1-thread-2 开始时间:16:20:27
pool-1-thread-2 结束时间:16:20:28
pool-1-thread-2 开始时间:16:20:28
pool-1-thread-1 结束时间:16:20:28
pool-1-thread-1 开始时间:16:20:28
pool-1-thread-3 结束时间:16:20:28
pool-1-thread-1 结束时间:16:20:29
pool-1-thread-2 结束时间:16:20:29
使用AbortPolicy策略后,线程任务数量超出线程池最大线程数时,线程池将抛出java.util.concurrent.RejectedExecutionException异常。
到此这篇关于 Java线程池使用AbortPolicy策略的文章就介绍到这了,更多相关Java AbortPolicy内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: Java线程池使用AbortPolicy策略
本文链接: https://www.lsjlt.com/news/153021.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0