如何在执行程序服务中获取队列中的任务数?

afr*_*gba 6 java multithreading executorservice threadpoolexecutor

所以我使用executorservice来创建一个线程池.

ExecutorService executor = Executors.newSingleThreadExecutor();
Run Code Online (Sandbox Code Playgroud)

我试图访问线程池队列中的任务数.我看到没有方法可以做到这一点.我知道有一些方法可以在threadpoolexecutor中获取队列大小,但是如何使用executorservice对象来实现这一点.

就像我说的,如果我创建了像这样的ThreadpoolExecutor,我可以获取队列信息

ThreadPoolExecutor tpExecutor =  new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>());
Run Code Online (Sandbox Code Playgroud)

我知道我可以使用tpExecutor.queue.size()来获取threadpool队列中的任务数.但是目前我已经使用Executor Service声明了我的线程池.我怎样才能做到这一点?如果人们可以编写代码并进行演示,那将是值得注意的.

tan*_*csg 7

我认为这应该有效:

    ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) this.executorService;
    int activeCount = threadPoolExecutor.getActiveCount();
    long taskCount = threadPoolExecutor.getTaskCount();
    long completedTaskCount = threadPoolExecutor.getCompletedTaskCount();
    long tasksToDo = taskCount - completedTaskCount - activeCount;
Run Code Online (Sandbox Code Playgroud)

由于某种原因,它并不总是排除所有已取消的任务,只有在进行一些定期清理之后才会排除。所以我不得不引入第二个计数器:

    long tasksToDo2 = threadPoolExecutor.getQueue().stream().filter(t -> !((FutureTask) t).isDone()).count();
Run Code Online (Sandbox Code Playgroud)


小智 -1

您可以将其强制转换为 ThreadPoolExecutor。

ThreadPoolExecutor ex=(ThreadPoolExecutor)执行器;ex.getQueue().size();

  • 它不起作用,因为 Executors.newSingleThreadExecutor() 返回仅公开 ExecutorService 方法的委托执行程序服务。我使用Java 1.8。我建议您查看源代码:http://www.fuseyism.com/classpath/doc/java/util/concurrent/Executors-source.html 如果您真的想获得线程池执行器,您将拥有要使用反射 API,我没有找到明智的解决方案。 (3认同)