没有队列的ThreadPoolExecutor [英] ThreadPoolExecutor without a Queue

查看:145
本文介绍了没有队列的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 是一个不包含任何对象的队列。缓存的线程池使用它,因为它根据需要创建新线程。

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:明确为什么要这样做会很有用。

BTW: It would be useful to make it clear why you want to do this.

这篇关于没有队列的ThreadPoolExecutor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆