I have some troubles using wait() and notify(). I need to have a kind of rendez-vous.
Here is the thing, in a small piece of code:
class A {
private Rdv r;
public A(Rdv r) {
this.r = r;
}
public void someMethod() {
synchronized(r) {
r.wait();
}
// ***** some stuff never reached*****
}
}
class Rdv {
private int added;
private int limit;
public Rdv(int limit) {
this.added = 0;
this.limit = limit;
}
public void add() {
this.added++;
if(this.added == this.limit) {
synchronized(this) {
this.notifyAll();
}
}
}
}
class Main {
public static void main(String[] args) {
Rdv rdv = new Rdv(4);
new Runnable() {
public void run() {
A a = new A(rdv);
a.someMethod();
}
}.run();
rdv.add();
rdv.add();
rdv.add();
rdv.add();
}
}
The idea is to wait until 4 threads tell “hey, i’m done” before to run the end of someMethod().
But the wait() lasts forever, despite of the notifyAll().
I don’t get how
wait()andnotify()are not meant to be used directly but rather are primitives that better libraries use for low-level synchronization.You should use a higher-level concurrency mechanism, such as
CountDownLatch. You would want to use aCountDownLatchwith a value of 4. Have each of the threads call thecountDown()method of the latch, and the one you want to wait to callawait().