没有队列的 ThreadPoolExecutor

ThreadPoolExecutor without a Queue(没有队列的 ThreadPoolExecutor)

本文介绍了没有队列的 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

基础教程推荐