从 Java 中的线程池中删除空闲线程?

Removing idle threads from thread pool in Java?

我正在使用 Java 固定大小的线程池 (ExecutorService)。假设我向线程池提交了一个作业并且该作业空闲了。

是否有可能从线程池中删除空闲作业,以便处理队列中的其他作业,然后再次添加空闲作业?

任务或 Runnable 可能在 idle 中(我想是在等待 I/O 或其他一些资源)这一事实是主要原因之一,因为适合于使用线程池。

另一方面,您要使用的线程数量是您需要调整的,以便在某些线程因等待资源而阻塞时允许处理任务。

您唯一需要做的就是观察线程进入空闲状态的频率并相应地调整线程数量。

调整线程池的指南(来自:IBM ThreadPools and Work Queue

Don't queue tasks that wait synchronously for results from other tasks. This can cause a deadlock of the form described above, where all the threads are occupied with tasks that are in turn waiting for results from queued tasks that can't execute because all the threads are busy.

Be careful when using pooled threads for potentially long-lived operations. If the program must wait for a resource, such as an I/O completion, specify a maximum wait time, and then fail or requeue the task for execution at a later time. This guarantees that eventually some progress will be made by freeing the thread for a task that might complete successfully.

Understand your tasks. To tune the thread pool size effectively, you need to understand the tasks that are being queued and what they are doing. Are they CPU-bound? Are they I/O-bound? Your answers will affect how you tune your application. If you have different classes of tasks with radically different characteristics, it may make sense to have multiple work queues for different types of tasks, so each pool can be tuned accordingly.

如果您从 ExecutorService 移动到 ThreadPoolExecutor,您可以通过以下 API

实现
public void setCorePoolSize(int corePoolSize)

Sets the core number of threads. This overrides any value set in the constructor. If the new value is smaller than the current value, excess existing threads will be terminated when they next become idle.

If larger, new threads will, if needed, be started to execute any queued tasks.

如果您想在 运行 时调整池的大小,

((ThreadPoolExecutor)service).setCorePoolSize(newLimit); //newLimit 是池的新大小

其他API:

public void setMaximumPoolSize(int maximumPoolSize)

Sets the maximum allowed number of threads. This overrides any value set in the constructor. If the new value is smaller than the current value, excess existing threads will be terminated when they next become idle.