簡體   English   中英

如何在執行程序服務中獲取隊列中的任務數?

[英]How to get the number of tasks in a queue in executor service?

所以我使用executorservice來創建一個線程池。

ExecutorService executor = Executors.newSingleThreadExecutor();

我試圖訪問線程池隊列中的任務數。 我看到沒有方法可以做到這一點。 我知道有一些方法可以在threadpoolexecutor中獲取隊列大小,但是如何使用executorservice對象來實現這一點。

就像我說的,如果我創建了像這樣的ThreadpoolExecutor,我可以獲取隊列信息

ThreadPoolExecutor tpExecutor =  new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>());

我知道我可以使用tpExecutor.queue.size()來獲取threadpool隊列中的任務數。 但是目前我已經使用Executor Service聲明了我的線程池。 我怎樣才能做到這一點? 如果人們可以編寫代碼並進行演示,那將是值得注意的。

我認為這應該有效:

    ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) this.executorService;
    int activeCount = threadPoolExecutor.getActiveCount();
    long taskCount = threadPoolExecutor.getTaskCount();
    long completedTaskCount = threadPoolExecutor.getCompletedTaskCount();
    long tasksToDo = taskCount - completedTaskCount - activeCount;

您可以將其強制轉換為ThreadPoolExecutor。

ThreadPoolExecutor ex =(ThreadPoolExecutor)executor; ex.getQueue()大小();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM