例如,在Pthreads中,有可能让一个进程等待某个条件成立,例如:
<await (nr == 0 ^ nw == 0) nw++>;
有没有使用Java中的信号量类似的方法来实现这个功能?等待条件,如nr==0。
例如,在Pthreads中,有可能让一个进程等待某个条件成立,例如:
<await (nr == 0 ^ nw == 0) nw++>;
如果这是一个一次性的事件,你可以使用CountDownLatch
:
private final CountDownLatch xIsZeroLatch = new CountDownLatch(1);
in your waiting thread:
xIsZeroLatch.await();
in the other thread(s):
x = newX();
if (x == 0) xIsZeroLatch.countDown();
Semaphore
。public void setX(int a) {
x = a;
if(x==0) {
//do stuff
}
}
然后使用该setter而不是x = a
。