如何监控所有由执行服务创建的线程的状态?

问题描述 投票:-2回答:1

有没有一种方法可以检查执行者服务创建的所有线程的状态。比如说我有20个线程。我如何检查所有线程的状态?

java multithreading executorservice java-threads
1个回答
1
投票

你可以扩展 ThreadPoolExecutor 并采用其方法 beforeExecute(Thread t, Runnable r)afterExecute(Runnable r, Throwable t) 来监控tasksthreads的状态。

你可以找到一个例子来实现 在本文


1
投票

如果你真的想监控线程池中所有线程的状态,你可以尝试像下面的代码一样创建你的ThreadFactory。

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;
    }
}

使用getStateMap()方法可以得到这个ThreadFactory创建的所有线程,然后可以得到线程的状态。

© www.soinside.com 2019 - 2024. All rights reserved.