簡體   English   中英

如何獲取當前正在運行的線程

[英]how to get currently running threads

我正在使用ThreadPoolExecutor來啟動處理來自阻塞隊列的請求的線程。 如果隊列為空,則所有這些工作線程都在等待。 這使得此池中的每個線程都處於等待狀態。

public ThreadPoolExecutor executor = new ThreadPoolExecutor(
                EngineConfiguration.numberOfSearchTask,
                EngineConfiguration.numberOfSearchTask + 10, 1000,
                TimeUnit.SECONDS, worksQueue, executionHandler);

我還啟動了下面的計划執行程序,它嘗試獲取上面池中的當前活動線程,當它為0時,它會關閉池:

final ScheduledFuture<?> scheduleFuture = scheduler
.scheduleAtFixedRate(new Runnable() {

    @Override
    public void run() {
        int activeThreadCount =   executor.getActiveThreads();
        if (activeThreadCount == 0) { 

SearchTaskRunner.keepRunning.set(false);
                log.warn("shutdown task runner");

            executor.shutdown();

            log.warn("shutdown scheduler");
            scheduler.shutdownNow();




        }
    }
}, 10, 10000, TimeUnit.SECONDS);

問題是10秒后,調度程序線程獲得activeThreadCount = 0,因此關閉池。

我們知道:

getActiveCount():返回正在執行任務的大致線程數。

這可能無法使准確數量的線程處於活動狀態。

無論如何我知道我的第一個池中的所有線程是否處於等待狀態?

用這個

Set<Thread> threadSet = Thread.getAllStackTraces().keySet();

使用此代碼獲取所有正在運行的線程並將set轉換為數組

Set<Thread> tSet = Thread.getAllStackTraces().keySet();
Thread[] tArray = tSet.toArray(new Thread[tSet.size()]);

暫無
暫無

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

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