Specifically, can somebody tell me what is wrong with this piece of code. It should start the threads, so should print "Entering thread.." 5 times and then wait until notifyAll() is called. But, it randomly prints "Entering.." and "Done.." and still keeps waiting on others.
public class ThreadTest implements Runnable {
private int num;
private static Object obj = new Object();
ThreadTest(int n) {
num=n;
}
@Override
public void run() {
synchronized (obj) {
try {
System.out.println("Entering thread "+num);
obj.wait();
System.out.println("Done Thread "+num);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Runnable tc;
Thread t;
for(int i=0;i<5;i++) {
tc = new ThreadTest(i);
t = new Thread(tc);
t.start();
}
synchronized (obj) {
obj.notifyAll();
}
}
}