Friday, 27 April 2018

InterThread Communication in multithreading..................................

How to use wait() and notify()
=====================================================================================================
package multithreading;

public class ThreadA {

public static void main(String[] args) throws InterruptedException {

ThreadB b=new ThreadB();
    b.start();
    synchronized (b) {
System.out.println("Main Thread calling wait method");
    b.wait();
    System.out.println("Main Thread got notification");
System.out.println("Result="+b.total);
}
}

}


===============================================================================================

package multithreading;

public class ThreadB  extends Thread
{
int total=0;

public void run()
{
synchronized (this) {
System.out.println("child thread starts calculation");
for(int i=1;i<=100;i++)
{
total=total+i;
}
System.out.println("child Thread giving notification");
this.notify();

}
}
}

===============================================================================================

o/p:-

Main Thread calling wait method
child thread starts calculation
child Thread giving notification
Main Thread got notification
Result=5050

 

No comments:

Post a Comment