Henry Wong wrote:
Basically, what is happening is that you are waiting on the same object used internally to implement join(). The join() method is implemented internally by doing a check on the isAlive() and doing a wait() on the thread object. When a thread completes, one of the tasks, after changing the thread to no longer be alive, is to send a notifyAll() on the thread object.
Or in other words, don't use the Thread object for wait() and notify() -- it is already being used.
Henry
In response to the discussion in
www.coderanch.com/t/489800/Programmer-Certification-SCJP/certification/Confusing-wait-notify
Sir,
As we know that before the termination of main
thread it waits for the other threads to terminate.. ie.. according to you it will implicitly call join() on each thread object.... that's right
also sir
this code..
view plaincopy to clipboardprint?
class ThreadA {
public static void main(
String [] args) {
ThreadB b = new ThreadB();
b.start();
synchronized(b) //1
{
try {
System.out.println("Waiting for b to complete...");
b.wait();
} catch (InterruptedException e) {}
System.out.println("Tota is: " + b.total);
}
}
}
class ThreadB extends Thread {
int total;
public void run( ) { //2
synchronized(this) {
for(int i=0;i<10;i++) {
total += i;
}
}
}
}
This can result on
wait..
as because it is not guaranteed that every time 1 will get first cpu time to execute.... It may happen that 2 get first and ten it will wait... because ... you are calling wait on the thread that has already terminated
Lets see another modification of this code..
view plaincopy to clipboardprint?
class ThreadA {
public static void main(String [] args) {
ThreadB b = new ThreadB();
b.start();
System.out.println("here 1 ");
System.out.println("here 2 ");
System.out.println("here 3 ");
System.out.println("here 4 ");
synchronized(b) {
try {
System.out.println("Waiting for b to complete...");
b.wait();
} catch (InterruptedException e) {}
System.out.println("Tota is: " + b.total);
}
}
}
class ThreadB extends Thread {
int total;
public void run( ) {
synchronized(this) {
for(int i=0;i<10;i++) {
total += i;
}
}
}
}
This will result in output
here 1
here 2
here 3
here 4
waiting for b to complete..
....................