In my java code the threadB creates nb*threadA and waits until the value of myobj will be equal to nb.
myobj is initially equal to 0 and each threadA increments it, when it becomes equal to nb the last threadA notifies the ThreadB.
When running the program the threadB is not notified and doesn’t continue running. Could anybody tell me where is the problem in this code?
public class Myclass {
static Long myobj = new Long(0);
static int nb = 1;
public static void main(String[] args) {
ThreadA[] threadA = new ThreadA[nb];
ThreadB threadB = new ThreadB(threadA);
}
}
public class ThreadA extends Thread {
public ThreadA() {
this.start();
}
public void run() {
// do lot of computation
Myclass.myobj = Myclass.myobj + 1;
if (Myclass.myobj.intValue() == Myclass.myobj.nb) {
synchronized (Myclass.myobj) {
Myclass.myobj.notify();
}
}
}
}
public class ThreadB extends Thread {
ThreadA[] threadA;
public ThreadB(ThreadA[] threadA) {
this.threadA = threadA;
this.start();
}
public void run() {
for (int i = 0; i < threadA.length; i++) {
threadA[i] = new ThreadA();
}
synchronized (Myclass.myobj) {
while (Myclass.myobj.intValue() != Myclass.myobj.nb) {
Myclass.myobj.wait();
}
}
}
}
You’re waiting on one object, and notifying on a different one, since ThreadA assigns a new object to Myclass.myobj and notifies this new object.
Use a dedicated lock object, and make sure EVERY access to myObj is guarded by this lock object.
Or better yet, use higher-level concurrency abstractions from the java.util.concurrent package.