java - 有没有办法确定 newFixedThreadPool 队列中有多少个可运行对象?

标签 java multithreading

我要火了

Executors.newFixedThreadPool(100);

在一个主程序中,生产者提供工作的速度比消费者跟上的速度快。有没有办法查看 newFixedThreadPool 使用的底层无界队列中有多少项在排队?

最佳答案

使用java.util.concurrent.ThreadPoolExecutor#getTaskCount获取线程池中的计划任务数量。但请注意,这只是一个近似值,可能并不准确。

如果你想解决生产者生产任务的速度比消费者快的问题,可以限制底层队列的大小,并在创建java时传入RejectedExecutionHandler的实现之一.util.concurrent.ThreadPoolExecutor。请参阅 ThreadPoolExecutor 文档中的以下代码片段:

Rejected tasks

New tasks submitted in method execute(java.lang.Runnable) will be rejected when the Executor has been shut down, and also when the Executor uses finite bounds for both maximum threads and work queue capacity, and is saturated. In either case, the execute method invokes the RejectedExecutionHandler.rejectedExecution(java.lang.Runnable, java.util.concurrent.ThreadPoolExecutor) method of its RejectedExecutionHandler. Four predefined handler policies are provided:

  1. In the default ThreadPoolExecutor.AbortPolicy, the handler throws a runtime RejectedExecutionException upon rejection.
  2. In ThreadPoolExecutor.CallerRunsPolicy, the thread that invokes execute itself runs the task. This provides a simple feedback control mechanism that will slow down the rate that new tasks are submitted.
  3. In ThreadPoolExecutor.DiscardPolicy, a task that cannot be executed is simply dropped.
  4. In ThreadPoolExecutor.DiscardOldestPolicy, if the executor is not shut down, the task at the head of the work queue is dropped, and then execution is retried (which can fail again, causing this to be repeated.)

It is possible to define and use other kinds of RejectedExecutionHandler classes. Doing so requires some care especially when policies are designed to work only under particular capacity or queuing policies.

关于java - 有没有办法确定 newFixedThreadPool 队列中有多少个可运行对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3655971/

相关文章:

java - 什么是NullPointerException,我该如何解决?

java - beanshell 采样器,我想从 jmeter 访问 java 代码

java - 在 AndEngine 中变换主体时崩溃

ruby - 确定 ruby 线程状态

multithreading - Goroutine I/O 调度

java - 数组写入竞争条件

c# - 异步和同步上下文

java - 反序列化图像对象数组

java - 为某些用户启用日志记录 Log4j

python - 异步多处理python