Hi,
class ThreadA {
public static void main(
String [] args) {
ThreadB b = new ThreadB("Thread B");
b.start();
synchronized(b) {
try {
System.out.println("Current
Thread: "+Thread.currentThread().getName());
System.out.println("Waiting for b to complete...");
b.wait(); } catch (InterruptedException e) {}
}
System.out.println("Total is: " + b.total);
}
}
class ThreadB extends Thread {
int total;
public ThreadB(String s)
{
super(s);
}
public void run()
{
System.out.println("Current Thread: "+Thread.currentThread().getName()+" Started");
synchronized(this)
{
System.out.println("Current Thread: "+Thread.currentThread().getName()+"Inside Synchronized Block in Run");
for(int i=0;i<100;i++)
{
total += i;
}
notify(); }
}
}
Actually there are two threads, one is the main thread and second one is the ThreadB instance. wait() method is invoked by the main thread and since
when wait() method is invoked on an object, the thread executing the code gives up its locks and goes to waiting (from K&B page 724). In this case the "main thread". The
notify method is invoked by the ThreadB instance which I think you are clear about.
Asha