简体   繁体   中英

How to monitor status of all threads created by executor service

Is there a way to check the status of all threads created by executor service. Let's say I have 20 threads. How would I check the status of all of them?

If you really want to monitor status of all threads in thread pool,you can try create your ThreadFactory like the below code:

public class SelfThreadFactory implements ThreadFactory {
    private Map<Long, Thread> stateMap = new ConcurrentHashMap<>();

    @Override
    public Thread newThread(Runnable r) {
        Thread thread = new Thread(r);
        stateMap.put(thread.getId(), thread);
        return thread;
    }

    public Map<Long, Thread> getStateMap() {
        return stateMap;
    }
}

Use getStateMap() method you can get all thread created by this ThreadFactory,then you can get state of thread.

You may extend ThreadPoolExecutor and use its methods beforeExecute(Thread t, Runnable r) and afterExecute(Runnable r, Throwable t) to monitor the status of the tasks/threads.

You can find an example implementation in this article

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM