gpt4 book ai didi

java - ThreadPoolExecutor 类似于 Executors.cachedThreadPool 但具有最大线程和队列

转载 作者:行者123 更新时间:2023-11-29 03:13:30 24 4
gpt4 key购买 nike

这是缓存的线程池:

new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>());

这是固定的 ThreadPoolExecutor:

new ThreadPoolExecutor( 0, 20, 60L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());

第一个可以创建 INTEGER.MAX_VALUE 个线程,这在我的例子中是不希望的。

第二个,不正确。您不能对 LinkedBlockingQueue 使用最少 0 个线程和最多 20 个线程。

来自文档:

http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ThreadPoolExecutor.html

Using an unbounded queue (for example a LinkedBlockingQueue without a predefined capacity) will cause new tasks to wait in the queue when all corePoolSize threads are busy. Thus, no more than corePoolSize threads will ever be created. (And the value of the maximumPoolSize therefore doesn't have any effect.)

在第一种情况下使用 SynchronousQueue,CachedThreadPool 实际上作为队列没有任何作用。它只会根据需要创建线程并且需要一个高上限。

A good default choice for a work queue is a SynchronousQueue that hands off tasks to threads without otherwise holding them. Here, an attempt to queue a task will fail if no threads are immediately available to run it, so a new thread will be constructed. This policy avoids lockups when handling sets of requests that might have internal dependencies. Direct handoffs generally require unbounded maximumPoolSizes to avoid rejection of new submitted tasks. This in turn admits the possibility of unbounded thread growth when commands continue to arrive on average faster than they can be processed.

现在,我所追求的是:

我想要的是一个你可以提交工作的执行器,如果 maxThreads 都忙,它会使用一个队列,但它也允许线程空闲,并且在没有工作时不占用任何资源。

使用:

ThreadPoolExecutor ex = new ThreadPoolExecutor(0, threads, 60L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
ex.setKeepAliveTime(idletime, TimeUnit.MILLISECONDS);

我不确定它有什么含义。该文档似乎只解释了无界 LinkedBlockingQueue 的使用,我不太确定这意味着什么,因为构造函数创建了一个最大容量为 Integer.MAX_VALUE 的队列。

文档还指出:

(And the value of the maximumPoolSize therefore doesn't have any effect.)

我想要的是最小线程池大小和最大线程池大小,用于排队工作并让线程在没有工作时空闲。

编辑

阅读这个问题和最后一部分让我考虑是否应该创建一个

new ThreadPoolExecutor(20, ??irrelevant??, 60L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue());

这将创建 20 个空闲线程,如果

ex.setKeepAliveTime(60L, TimeUnit.MILLISECONDS);

已设置。

这是一个正确的假设吗?

最佳答案

也许这有帮助:https://stackoverflow.com/a/19538899/999043 (如何让ThreadPoolExecutor在排队前增加线程到max?)

关于java - ThreadPoolExecutor 类似于 Executors.cachedThreadPool 但具有最大线程和队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27987724/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com