ThreadPoolExecutor without a Queue(没有队列的 ThreadPoolExecutor)
问题描述
我想创建一个固定大小的线程池,它不允许任何任务进入其队列.换句话说,如果线程池当前正在使用,那么传入的任务应该被彻底拒绝.基于 文档,一种方法在我看来,要做到这一点,就是创建一个拒绝接受任务的虚拟 Queue 对象.在 Java 中实现这一点的惯用方法是什么?
I want to create a fixed-size thread pool that admits no task into its queue. In other words, if the thread pool is currently in use, the incoming task should be rejected outright. Based on the documentation, one way to do this, in my opinion, would be to create a dummy Queue object which refuses to admit a task. What is the idiomatic way to accomplish this in Java?
推荐答案
你可以使用 SynchronousQueue 在您的 ThreadPoolExector 中,这是一个不包含任何对象的队列.缓存线程池使用它是因为它按需创建新线程.
You can use a SynchronousQueue in your ThreadPoolExector which is a queue which holds no objects. The cached thread pool uses this because it creates new threads on demand.
如果无法排队,但我建议使用 RejectedExecutionHandler 在当前线程中运行任务.这样,它将始终立即"运行.
If it cannot be queued but I would suggest using the RejectedExecutionHandler to run the task in the current thread. This way it will always be run "immediately".
顺便说一句:说明你为什么要这样做会很有用.
BTW: It would be useful to make it clear why you want to do this.
这篇关于没有队列的 ThreadPoolExecutor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:没有队列的 ThreadPoolExecutor


- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01