出于调试目的,我想监听线程状态。我希望它在线程等待日志时以及“恢复”时打印通知。
最佳答案
鉴于您无法在 java.lang.Thread
上以 that variable is managed by native code 收听 private volatile int threadStatus;
我能想到的唯一方法是拥有一个并行线程,其方法每 x 毫秒/秒运行一次并适当输出。
// keep old values in a map like this
HashMap<Thread, ThreadStatus> threadMap;
// loop all threads
Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
ArrayList<Thread> threadArrayList = new ArrayList<>(threadSet);
for (Thread thread : threadArrayList) {
// check if thread.getState() has changed, update accordingly
}
请注意,除了效率不高之外,您还会错过很多会在亚毫秒内发生的 ThreadStatus 更改。
关于Java 监听线程状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39257711/