当线程状态改变时,有没有办法在进程中获得通知?我正在编写一个监控线程状态变化的程序。我可以频繁地轮询每个线程,但我更喜欢更具反应性的东西。
发布于 2018-11-05 16:18:32
可以,使用conditional variable,示例如下:
import java.util.concurrent.locks.*;
public class CubbyHole2 {
private int contents;
private boolean available = false; // this is your state
private Lock aLock = new ReentrantLock(); // state must be protected by lock
private Condition condVar = aLock.newCondition(); // instead of polling, block on a condition
public int get(int who) {
aLock.lock();
try {
// first check state
while (available == false) {
try {
// if state not match, go to sleep
condVar.await();
} catch (InterruptedException e) { }
}
// when status match, do someting
// change status
available = false;
System.out.println("Consumer " + who + " got: " +
contents);
// wake up all sleeper than wait on this condition
condVar.signalAll();
} finally {
aLock.unlock();
return contents;
}
}
public void put(int who, int value) {
aLock.lock();
try {
while (available == true) {
try {
condVar.await();
} catch (InterruptedException e) { }
}
contents = value;
available = true;
System.out.println("Producer " + who + " put: " +
contents);
condVar.signalAll();
} finally {
aLock.unlock();
}
}
}发布于 2018-11-05 16:25:36
线程运行的代码需要注入代码,以便在状态发生变化时进行回调。您可以按照@宏杰李的建议更改代码,或者使用Instrumentation注入代码,但是轮询线程可能是最简单的。
注意:从JVM的角度来看,线程的状态只告诉您它想要的状态。它不会显示你
顺便说一句,甚至操作系统也会轮询CPU以查看它们在做什么,通常每秒100次。
https://stackoverflow.com/questions/53150276
复制相似问题