如何获取执行程序服务中队列中的任务数量?
问题描述:
所以我使用executorservice来创建一个线程池。如何获取执行程序服务中队列中的任务数量?
ExecutorService executor = Executors.newSingleThreadExecutor();
我试图访问该线程池的队列中的任务数。我发现没有办法去解决这个问题。 我知道有一些方法可以在threadpoolexecutor中获得队列大小,但是我怎么用executorservice对象来做到这一点。
就像我说的,我可以得到队列的信息,如果我创建了这样的
ThreadPoolExecutor tpExecutor = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>());
我知道我可以使用tpExecutor.queue.size(),以获得在队列中的任务数量的ThreadPoolExecutor线程池。 但目前我已经使用Executor Service声明了我的线程池。我怎样才能做到这一点? 如果人们可以编写代码并演示,那将是可观的。
答
您可以将其转换为ThreadPoolExecutor。
ThreadPoolExecutor ex =(ThreadPoolExecutor)executor; ex.getQueue()。size();
'Executors.newFixedThreadPool(nThreads)'哪里'nThreads = 1'? – nullpointer
我能从中得到什么?我如何获得线程池队列中的任务数量?请详细说明。 – africandrogba
假设'newSingleThreadExecutor()'实际上返回了一个'ThreadPoolExector'类型,您可以只投出对象并调用https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ ThreadPoolExecutor.html#getActiveCount--不知道为什么这很重要。 – markspace