Inter communication between threads in java

Java provides a very efficient way which multiple threads can communicate with each other. This way reduces the CPU’s idle time i.e. A process where, a thread is paused running in its critical region and another thread is allowed to enter (or lock) in the same critical section to be executed. This technique is known as Inter thread communication which can be implemented by some methods. And these methods come with all the java objects.

• wait()

• notify()

• notifyAll()

All three above methods are java.lang.Object class method. So these methods come in all java objects. But to achieve the inter communication between thread these method must be used in synchronized block or method.

To understand the inter communication between threads we will take one example and implement it by thread communication.

package com.java.connect.thread;
 
public class ExampleWait extends Thread {
    int value = 500;
 
    public static void main(String args[]) {
        ExampleWait d = new ExampleWait();
        d.start();
        new Example1(d);
    }
 
    public void run() {
        try {
            synchronized (this) {
                wait();
                System.out.println("the value is  :" + value);
            }
        } catch (Exception e) {
        }
    }
 
    public void changeValue(int val) {
        this.value = val;
        try {
            synchronized (this) {
                notifyAll();
            }
        } catch (Exception e) {
        }
 
    }
}
 
class Example1 extends Thread {
    ExampleWait wait;
 
    Example1(ExampleWait d) {
        this.wait = d;
        start();
    }
 
    public void run() {
        try {
            System.out.println("Example1 value is" + wait.value);
            wait.changeValue(400);
        } catch (Exception e) {
        }
    }
}