没有队列的 ThreadPoolExecutor

2022-01-21 00:00:00 queue threadpool java

我想创建一个固定大小的线程池,它不允许任何任务进入其队列.换句话说,如果线程池当前正在使用,那么传入的任务应该被彻底拒绝.基于 文档,一种方法在我看来,要做到这一点,就是创建一个拒绝接受任务的虚拟 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.

相关文章