Equivalent to wait (x == 0) in Java
In, for example, Pthreads it is possible to wait for a process for a certain condition, for example:
<await (nr == 0 ^ nw == 0) nw++>;
Is there a way to do this in a similar way using Semaphores in Java? Waiting for a condition such as nr == 0.
+3
Rickard
source
to share
2 answers
If it's a one-off event, you can use aCountDownLatch
:
private final CountDownLatch xIsZeroLatch = new CountDownLatch(1);
Then you use it like this:
-
in a waiting thread:
xIsZeroLatch.await();
-
in the other thread (s):
x = newX(); if (x == 0) xIsZeroLatch.countDown();
If a condition can change multiple times between true and false, and each change requires an event, you can use Semaphore
with one resolution.
+4
assylias
source
to share
public void setX(int a) {
x = a;
if(x==0) {
//do stuff
}
}
Then use this installer instead x = a
.
0
Doorknob
source
to share