Communication between Threads

Frequently, threads will need to coordinate between themselves, especially when the output of one thread is used by another thread. Let us consider the classical “The Producer-Consumer Problem” in which one part of the program is writing data and another part of it is reading data – but sometimes the reading part gets ahead of the writing part. We can solve this problem by communicating between the threads. One way of coordinating threads is to use the wait(), notify(), and notifyAll() methods.

Here is an example. In this case, a writer thread will call an object’s write() method to write some data, and a reader thread will call the same object’s read() method to read the result. Obviously, we want the reader thread to wait until write() method is finished. Therefore, all we have to do is call wait() in read() method to make the reader thread wait and call notify() in write() method when the writer thread is finished and the data is ready to be read. See the code below:

InterThreadComn.java

public class InterThreadComn {

public static void main(String[] args) {
Share sh = new Share();
Reader t1 = new Reader(sh, "1st");
Writer t2 = new Writer(sh, "2nd");
}
}

class Share {
int data = 0;

synchronized void write() {
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
System.out.println(e);
}
data = 100;
notify();
}

synchronized int read() {
try {
wait();
}
catch (InterruptedException e) {
System.out.println(e);
}
return data;
}
}

class Reader extends Thread {
Share sh;

public Reader(Share sh, String name) {
super(name);
this.sh = sh;
start();
}

public void run() {
System.out.println("Result: " + sh.read());
}
}

class Writer extends Thread {
Share sh;

public Writer(Share sh, String name) {
super(name);
this.sh = sh;
start();
}

public void run() {
sh.write();
}
}

Output:
Result: 100

 

 

Differences between wait() and sleep() methods

The differences between these two methods are listed below.

wait() method

Sl. No.

sleep() method

wait() is the method of java.lang.Object class.

1

sleep() is the method of java.lang.Thread class.

wait() method releases the lock.

2

sleep() method doesn’t release the lock.

wait() is used for inter-thread communication.

3

sleep() is generally used to introduce a pause on execution.

wait() is the non-static (i.e. instance) method – 

public final void wait() throws InterruptedException { //… }

4

sleep() is the static method –

public static void sleep (long milliseconds) throws InterruptedException { //… }

 

wait() should be notified by notify() or notifyAll() methods.

 

5

After the specified amount of time, sleep() is completed.

 

wait() method must be called from synchronized context  (i.e. synchronized method or block), otherwise it will throw IllegalMonitorStateException.

6

sleep() may be called from anywhere. there is no specific requirement.