Wednesday, February 25, 2009

source code to demonstrate wait notify methods



package thread;

public class ThreadA
{
public static void main(String[]args)throws InterruptedException
{
ThreadB b =new ThreadB();
b.start();
synchronized(b) //thread got lock
{
System.out.println("iam calling wait method");
b.wait();
System.out.println("I got notification");
}
System.out.println(b.total);
}
}
class ThreadB extends Thread
{
int total=0;
public void run()
{
synchronized (this)//.thread got lock
{
System.out.println("iam starting calculation");
for(int i=0;i<=1000;i++)
{
total=total+i;
}
System.out.println("iam giving notification call");
notify(); //thread releases lock again
}
}
}

output:
iam calling wait method
iam starting calculation
iam giving notification call
I got notification
500500


3 comments:

Anonymous said...

Can Any one explain it to me the flow of execution please...

Anonymous said...

hello i have doubt

srinivasarao guptha said...

hi i want to know where we will use thread concept in real time applications.please let me know

Post a Comment