Inter Thread Communication
In this tutorial, we are going to discuss about Inter Thread Communication in java. Inter thread communication in Java refers to the coordination and exchange of data between threads to achieve synchronization and cooperation in a multi-threaded environment. Inter thread communication is also known as Cooperation in Java.
- In Java, there are two ways to implement inter thread communication: using wait() and notify() methods and using the higher-level constructs of the java.util.concurrent package.
- Two threads can communicate with each other by using wait(), notify(), notifyAll().
- These methods are available in object class but not in thread class. Because threads are calling these methods on any object.
- If a thread wants to call wait(), notify() and notifyAll() methods compulsory the Thread should be owner of the object. i.e., the Thread has to get lock of that object. i.e., the Thread should be in the synchronized area.
- Hence, We should call these methods only from synchronized area other wise we get runtime exception saying IllegalMonitorStateException.
- If a thread executes wait() method it immediately releases the lock of that object(But not all locks) and entered into waiting state.
- Thread releases the lock of only current object but not all locks. After calling notify() and notifyAll() methods Thread releases the lock but not immediately. Except these wait(), notify(), notifyAll() there is no other case where Thread releases the lock.
public final void wait() throws InterruptedException
public final native void wait(long ms) throws InterruptedException
public final void wait(long ms,int ns) throws InterruptedException
public final native void notify()
public final void notifyAll()
package com.ashok.threads;
/**
*
* @author ashok.mariyala
*
*/
public class Test {
public static void main(String arg[]) throws InterruptedException {
MyThread thread = new MyThread();
thread.start();
System.out.println("Inside Main Method");
Thread.sleep(100);
System.out.println(thread.total);
}
}
class MyThread extends Thread {
int total = 0;
public void run() {
System.out.println("Child Starting calculation");
for (int i = 1; i <= 50; i++) {
if (i == 1)
System.out.println("Inside for loop ");
total = total + i;
}
}
}
Output
Inside Main Method
Child Starting calculation
Inside for loop
1275
Here we used sleep() method to give chance to child thread. But we can’t say child thread will finish his work with in given time. So we may get unusually outputs. There is no Guaranteed Output.
package com.ashok.threads;
/**
*
* @author ashok.mariyala
*
*/
public class Test {
public static void main(String arg[]) throws InterruptedException {
MyThread thread = new MyThread();
thread.start();
synchronized (thread) {
System.out.println("Main Method calling wait method ");
thread.wait();
System.out.println("Main Got Notification");
System.out.println(thread.total);
}
}
}
class MyThread 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
Main Method calling wait method
Child Starting calculation
Child Giving notification
Main Got Notification
1275
notify() vs notifyAll()
- We can use notify() method to give notification for only one Thread. If multiple Threads are waiting then only one Thread will get the chance and remaining Threads has to wait for further notification. But which Thread will be notify(inform) we can’t expect exactly it depends on JVM.
- We can use notifyAll() method to give the notification for all waiting Threads. All waiting Threads will be notified and will be executed one by one, because they are required lock
Note
On which object we are calling wait(), notify() and notifyAll() methods that corresponding object lock we have to get but not other object locks.
E.g
Producer consumer problem
- Producer(producer Thread) will produce the items to the queue and consumer(consumer thread) will consume the items from the queue. If the queue is empty then consumer has to call wait() method on the queue object then it will entered into waiting state.
- After producing the items producer Thread call notify() method on the queue to give notification so that consumer Thread will get that notification and consume items.
When using inter-thread communication, it’s crucial to handle exceptions and edge cases gracefully to avoid deadlocks, livelocks, and other concurrency issues.
That’s all about Inter Thread Communication in java. If you have any queries or feedback, please write us at contact@waytoeasylearn.com. Enjoy learning, Enjoy Java.!!