Friday, February 24, 2017

Interthread Communication in Java

In this article i am sharing interthread communication in Java. This is one of the core concept in Core Java,there is possibility many interview questions raised from this topic and at the same time this topic is also helpful for written Test. Java includes elegant inter process communication mechanism via wait(),notify() and notifyAll() methods. These methods are implemented as final methods in Object class.You must notice one thing is you have to these three methods within the synchronized context only otherwise we will get runtime exception saying IllegalMonitorStateException.All these three methods are available in Object class only but not Thread class. Because threads are calling these methods on any object.

The following are the rules to use these methods:

wait(): This methods tells calling the thread to give up the monitor and go to sleep until some other thread enters same the same monitor and calls notify() and notifyAll().

notify(): This method wake up a thread that called wait() method on the same object

notifyAll(): This method wakes up all threads that  called wait() method on the same object.

These methods are declared within the object as shown below:

final void wait() throws InterrruptedException
final void notify()
final void notifyAll()


Example:

class ThreadA
{
public static void main(String arg[])throws InterruptedException
{
ThreadB b = new ThreadB();
b.start();
synchronized(b)
{
System.out.println("Main Method calling wait method ");
b.wait();
System.out.println("Main Got Notification");
System.out.println(b.total);
}
}
}
class ThreadB extends Thread
{
int total = 0;
public void run()
{
synchronized(this)
{
System.out.println("Child Starting calculation");
for(int i = 1; i<=100; i++)
{
total = total + i;
}
System.out.println("Child giving notification");
this.notify();
}
}

}

Output:








Recommended to Read:

Synchronization Interview Questions
Java Multithreading Examples
Java Multithreading Interview Questions
Life cycle of Thread in Java

No comments:

Post a Comment

High Paying Jobs after Learning Python

Everyone knows Python is one of the most demand Programming Language. It is a computer programming language to build web applications and sc...