In the below example, as the main-thread is not getting notified from the child thread, it should wait forever. But the main-thread is getting executed and the output of the below example is:
c
l
total: 19900
Why is the main-thread getting executed?
public class ThreadX extends Thread {
static int total = 0;
public void run() {
synchronized (this) {
for (int i = 0; i < 200; i++) {
total = total + i;
}
System.out.println("c");
}
}
public static void main(String[] args) throws InterruptedException {
ThreadX t = new ThreadX();
t.start();
synchronized (t) {
t.wait();
System.out.println("l");
}
System.out.println("total: " + total);
}
}
notify
to your thread object. Better use a dedicated monitor object not something that might already participate in notification for other purposes. – Eleemosynary