当线程更改状态时,是否可以通过任何方式获取通知?我正在编写一个监视线程状态变化的程序。我可以经常轮询每个线程,但我希望使用更多响应式的东西。
答案 0 :(得分:1)
是的,使用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();
}
}
}
答案 1 :(得分:0)
您运行的线程的代码需要注入代码以进行状态更改的回调。您可以按照@宏杰李的建议更改代码或使用Instrumentation
注入代码来完成此操作,但是轮询线程可能是最简单的。
注意:从JVM的角度来看,线程的状态仅告诉您所需的状态。它不显示你
顺便说一句,甚至OS也会轮询CPU以查看其运行情况,通常每秒进行100次。