The Wayback Machine - https://web.archive.org/web/20241013215407/https://www.geeksforgeeks.org/inter-thread-communication-java/
Open In App

Inter-thread Communication in Java

Last Updated : 06 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Prerequisite: Multithreading in Java, Synchronized in Java 

Inter-thread communication in Java is a mechanism in which a thread is paused running in its critical section and another thread is allowed to enter (or lock) in the same critical section to be executed.

Note: Inter-thread communication is also known as Cooperation in Java.

What is Polling, and what are the problems with it? 

The process of testing a condition repeatedly till it becomes true is known as polling. Polling is usually implemented with the help of loops to check whether a particular condition is true or not. If it is true, a certain action is taken. This wastes many CPU cycles and makes the implementation inefficient. 

For example, in a classic queuing problem where one thread is producing data, and the other is consuming it.

How Java Multi-Threading tackles this problem? 

To avoid polling, Java uses three methods, namely, wait(), notify(), and notifyAll(). All these methods belong to object class as final so that all classes have them. They must be used within a synchronized block only. 

  • wait(): It tells the calling thread to give up the lock and go to sleep until some other thread enters the same monitor and calls notify().
  • notify(): It wakes up one single thread called wait() on the same object. It should be noted that calling notify() does not give up a lock on a resource.
  • notifyAll(): It wakes up all the threads called wait() on the same object.
Java Multithreading Tackles Polling

Example:

A simple Java program to demonstrate the three methods. Please note that this program might only run in offline IDEs as it contains taking input at several points.

Java
import java.util.LinkedList;
import java.util.Queue;

public class ProducerConsumer {
    // Shared queue used by both producer and consumer
    private static final Queue<Integer> queue = new LinkedList<>();
    // Maximum capacity of the queue
    private static final int CAPACITY = 10;

    // Producer task
    private static final Runnable producer = new Runnable() {
        public void run() {
            while (true) {
                synchronized (queue) {
                    // Wait if the queue is full
                    while (queue.size() == CAPACITY) {
                        try {
                            System.out.println("Queue is at max capacity");
                            queue.wait(); // Release the lock and wait
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    // Add item to the queue
                    queue.add(10);
                    System.out.println("Added 10 to the queue");
                    queue.notifyAll(); // Notify all waiting consumers
                    try {
                        Thread.sleep(2000); // Simulate some delay in production
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    };

    // Consumer task
    private static final Runnable consumer = new Runnable() {
        public void run() {
            while (true) {
                synchronized (queue) {
                    // Wait if the queue is empty
                    while (queue.isEmpty()) {
                        try {
                            System.out.println("Queue is empty, waiting");
                            queue.wait(); // Release the lock and wait
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    // Remove item from the queue
                    System.out.println("Removed " + queue.remove() + " from the queue");
                    queue.notifyAll(); // Notify all waiting producers
                    try {
                        Thread.sleep(2000); // Simulate some delay in consumption
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    };

    public static void main(String[] args) {
        System.out.println("Main thread started");
        // Create and start the producer thread
        Thread producerThread = new Thread(producer, "Producer");
        // Create and start the consumer thread
        Thread consumerThread = new Thread(consumer, "Consumer");
        producerThread.start();
        consumerThread.start();
        System.out.println("Main thread exiting");
    }
}

Explanation of the above Program:

Queue Initialization:

private static final Queue<Integer> queue = new LinkedList<>();
private static final int CAPACITY = 10;
  • A shared queue (LinkedList implementation) is defined with a capacity of 10. This queue will be used by both producer and consumer threads to add and remove items.

Producer Runnable:

private static final Runnable producer = new Runnable() {
public void run() {
while (true) {
synchronized (queue) {
while (queue.size() == CAPACITY) {
try {
System.out.println("Queue is at max capacity");
queue.wait(); // Release the lock and wait
} catch (InterruptedException e) {
e.printStackTrace();
}
}
queue.add(10);
System.out.println("Added 10 to the queue");
queue.notifyAll(); // Notify all waiting consumers
try {
Thread.sleep(2000); // Simulate some delay in production
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
};
  • Infinite Loop: The producer runs in an infinite loop, continuously producing items.
  • Synchronization: The block is synchronized on the shared queue to ensure thread safety.
  • Capacity Check: If the queue is full (queue.size() == CAPACITY), the producer waits (queue.wait()) until notified by a consumer.
  • Add Item: If there is space in the queue, the producer adds an item (queue.add(10)).
  • Notify Consumers: After adding an item, it notifies all waiting consumers (queue.notifyAll()).
  • Simulate Delay: The producer sleeps for 2 seconds to simulate the production time (Thread.sleep(2000)).

Consumer Runnable:

private static final Runnable consumer = new Runnable() {
public void run() {
while (true) {
synchronized (queue) {
while (queue.isEmpty()) {
try {
System.out.println("Queue is empty, waiting");
queue.wait(); // Release the lock and wait
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Removed " + queue.remove() + " from the queue");
queue.notifyAll(); // Notify all waiting producers
try {
Thread.sleep(2000); // Simulate some delay in consumption
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
};
  • Infinite Loop: The consumer runs in an infinite loop, continuously consuming items.
  • Synchronization: The block is synchronized on the shared queue to ensure thread safety.
  • Empty Check: If the queue is empty (queue.isEmpty()), the consumer waits (queue.wait()) until notified by a producer.
  • Remove Item: If there are items in the queue, the consumer removes an item (queue.remove()).
  • Notify Producers: After removing an item, it notifies all waiting producers (queue.notifyAll()).
  • Simulate Delay: The consumer sleeps for 2 seconds to simulate the consumption time (Thread.sleep(2000)).

Main Method:

public static void main(String[] args) {
System.out.println("Main thread started");
// Create and start the producer thread
Thread producerThread = new Thread(producer, "Producer");
// Create and start the consumer thread
Thread consumerThread = new Thread(consumer, "Consumer");
producerThread.start();
consumerThread.start();
System.out.println("Main thread exiting");
}
  • Main Thread Start: The main method starts by printing a message.
  • Create Threads: Two threads are created for the producer and consumer, respectively (Thread producerThread = new Thread(producer, "Producer") and Thread consumerThread = new Thread(consumer, "Consumer")).
  • Start Threads: Both threads are started (producerThread.start() and consumerThread.start()).
  • Main Thread Exit: The main method prints an exit message and terminates.

Output:

The program will produce output similar to this:

Main thread started
Main thread exiting
Queue is empty, waiting
Added 10 to the queue
Removed 10 from the queue
Queue is empty, waiting
Added 10 to the queue
Removed 10 from the queue
...

This output shows the interaction between the producer and consumer, where the producer adds items to the queue, and the consumer removes them. When the queue is full, the producer waits, and when the queue is empty, the consumer waits, demonstrating inter-thread communication using wait() and notifyAll() methods.

This example effectively demonstrates inter-thread communication in Java using a typical producer-consumer problem, showcasing the practical use of wait(), notifyAll(), and synchronization.



Previous Article
Next Article

Similar Reads

Why Thread.stop(), Thread.suspend(), and Thread.resume() Methods are Deprecated After JDK 1.1 Version?
The Thread class contains constructors and methods for creating and operating on threads. Thread is a subclass of Object that implements the Runnable interface. There are many methods in Thread Class but some of them are deprecated as of JDK 1.1. In this article, we will understand the reason behind it. Deprecated methods are those that are no long
5 min read
Difference between Thread.start() and Thread.run() in Java
In Java's multi-threading concept, start() and run() are the two most important methods. Below are some of the differences between the Thread.start() and Thread.run() methods: New Thread creation: When a program calls the start() method, a new thread is created and then the run() method is executed. But if we directly call the run() method then no
3 min read
Naming a thread and fetching name of current thread in Java
Thread can be referred to as a lightweight process. Thread uses fewer resources to create and exist in the process; thread shares process resources. The main thread of Java is the thread that is started when the program starts. now let us discuss the eccentric concept of with what ways we can name a thread. Methods: There are two ways by which we c
5 min read
Java.lang.Thread Class in Java
Thread is a line of execution within a program. Each program can have multiple associated threads. Each thread has a priority which is used by the thread scheduler to determine which thread must run first. Java provides a thread class that has various method calls in order to manage the behavior of threads by providing constructors and methods to p
8 min read
Daemon Thread in Java
In Java, daemon threads are low-priority threads that run in the background to perform tasks such as garbage collection or provide services to user threads. The life of a daemon thread depends on the mercy of user threads, meaning that when all user threads finish their execution, the Java Virtual Machine (JVM) automatically terminates the daemon t
4 min read
Thread Interference and Memory Consistency Errors in Java
Java allows multithreading which involves concurrent execution of two or more parts of the program. It enhances CPU utilization by performing multiple tasks simultaneously. The threads communicate with each other by sharing object references and member variables. When Two threads access the same shared memory This communication in multithreading ca
5 min read
Lock framework vs Thread synchronization in Java
Thread synchronization mechanism can be achieved using Lock framework, which is present in java.util.concurrent package. Lock framework works like synchronized blocks except locks can be more sophisticated than Java’s synchronized blocks. Locks allow more flexible structuring of synchronized code. This new approach was introduced in Java 5 to tackl
5 min read
Thread Safety and how to achieve it in Java
As we know Java has a feature, Multithreading, which is a process of running multiple threads simultaneously. When multiple threads are working on the same data, and the value of our data is changing, that scenario is not thread-safe and we will get inconsistent results. When a thread is already working on an object and preventing another thread on
5 min read
How to Create a Thread-Safe ConcurrentHashSet in Java?
Creating Thread Safe ConcurrentHashSet is not possible before JDK 8 because of the java.util.concurrent package does not have a class called ConcurrentHashSet, but starting with JDK 8, the newly added keySet (the default) and newKeySet() methods to create a ConcurrentHashSet in Java that is supported by ConcurrentHashMap. ConcurrentHashSet can be c
4 min read
Thread.sleep() Method in Java With Examples
Thread Class is a class that is basically a thread of execution of the programs. It is present in Java.lang package. Thread class contains the Sleep() method. There are two overloaded methods of Sleep() method present in Thread Class, one is with one argument and another one is with two arguments. The sleep() method is used to stop the execution of
4 min read
Importance of Thread Synchronization in Java
Our systems are working in a multithreading environment that becomes an important part for OS to provide better utilization of resources. The process of running two or more parts of the program simultaneously is known as Multithreading. A program is a set of instructions in which multiple processes are running and within a process, multiple threads
10 min read
How Does ConcurrentHashMap Achieve Thread-Safety in Java?
ConcurrentHashMap is a hash table supporting full concurrency of retrievals and high expected concurrency for updates. This class obeys the same functional specifications as Hashtable and includes all methods of Hashtable. ConcurrentHashMap is in java.util.Concurrent package. Syntax: public class ConcurrentHashMap<K,V> extends AbstractMap<
6 min read
run() Method in Java Thread
The run() method is available in the thread class constructed using a separate Runnable object. Otherwise, this method does nothing and returns. We can call the run() method multiple times. The run() method can be called in two ways which are as follows: Using the start() method.Using the run() method itself. Syntax: public void run() { //statement
3 min read
How to Create Thread using Lambda Expressions in Java?
Lambda Expressions are introduced in Java SE8. These expressions are developed for Functional Interfaces. A functional interface is an interface with only one abstract method. To know more about Lambda Expressions click here. Syntax: (argument1, argument2, .. argument n) -> { // statements }; Here we make use of the Runnable Interface. As it is
3 min read
Java Thread Priority in Multithreading
As we already know java being completely object-oriented works within a multithreading environment in which thread scheduler assigns the processor to a thread based on the priority of thread. Whenever we create a thread in Java, it always has some priority assigned to it. Priority can either be given by JVM while creating the thread or it can be gi
5 min read
Main thread in Java
Java provides built-in support for multithreaded programming. A multi-threaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution.When a Java program starts up, one thread begins running immediately. This is usually called the main thread
4 min read
Thread Pools in Java
Background Server Programs such as database and web servers repeatedly execute requests from multiple clients and these are oriented around processing a large number of short tasks. An approach for building a server application would be to create a new thread each time a request arrives and service this new request in the newly created thread. Whil
9 min read
Implement Runnable vs Extend Thread in Java
As discussed in Java multi-threading article we can define a thread in the following two ways: By extending Thread class By implementing Runnable interface In the first approach, Our class always extends Thread class. There is no chance of extending any other class. Hence we are missing Inheritance benefits. In the second approach, while implementi
2 min read
Thread isAlive() Method in Java With Examples
Thread class in java provides numerous methods that are very essential in order to understand the working of threads as the thread stages are triggered by them. Java multi-threading provides two ways to find with the help of isAlive() and join() method.One thread gets to know when another thread has ended. Let us do depict stages of the lifecycle o
2 min read
Interrupting a Thread in Java
In Java Threads, if any thread is in sleeping or waiting state (i.e. sleep() or wait() is invoked), calling the interrupt() method on the thread, breaks out the sleeping or waiting state throwing InterruptedException. If the thread is not in the sleeping or waiting state, calling the interrupt() method performs normal behavior and doesn't interrupt
3 min read
Lifecycle and States of a Thread in Java
A thread in Java at any point of time exists in any one of the following states. A thread lies only in one of the shown states at any instant: New StateRunnable StateBlocked StateWaiting StateTimed Waiting StateTerminated StateThe diagram shown below represents various states of a thread at any instant in time. Life Cycle of a Thread There are mult
6 min read
Servlet - Single Thread Model Interface
Single Thread Model Interface was designed to guarantee that only one thread is executed at a time in a given servlet instance service method. It should be implemented to ensure that the servlet can handle only one request at a time. It is a marker interface and has no methods. Once the interface is implemented the system guarantees that there's ne
3 min read
Overriding of Thread class start() method
Whenever we override start() method then our start() method will be executed just like a normal method call and new thread wont be created. We can override start/run method of Thread class because it is not final. But it is not recommended to override start() method, otherwise it ruins multi-threading concept. // Java program illustrate the concept
2 min read
Overloading of Thread class run() method
Overloading of run() method is possible. But Thread class start() method can invoke no-argument method. The other overloaded method we have to call explicitly like a normal method call. // Java Program to illustrate the behavior of // run() method overloading class Geeks extends Thread { public void run() { System.out.println("GeeksforGeeks
2 min read
Communication Between two Programs using JSON
JSON stands for JavaScript Object Notation. To communicate between computer and human we use a programming language. To communicate between two programs, there must be a common data format and here we use JSON format. Let us say you have an application with Frontend written in Python and Backend written in Java. Now you need to communicate between
3 min read
Different Ways to Establish Communication Between Spring Microservices
If you are working with a Spring Boot project which involves multiple microservices, You might have felt the need to communicate from microservice m1 to microservice m2. Depending upon business use-cases, this communication can be of synchronous or asynchronous type. Before digging dip further. Let's understand the use-case first. There are two mic
3 min read
Understanding USB Communication in Android Apps
In this article, we are going to see how to interact with USB in Android apps. What things are Required and Also 1 mini Project to Get a Clear Idea of How Things Work When We Need to Interact Android Apps With USB. USB Endpoints and InterfacesEndpoints:Endpoints are the channels through which data is transferred between the USB device and the host
7 min read
Spring Boot Microservices Communication using RestTemplate with Example
RestTemplate is a synchronous REST client which performs HTTP requests using a simple template-style API. We can also state that RestTemplate class is a synchronous client and is designed to call REST services. Apart from that, RestTemplate class plays a major role whenever we talk about Spring Boot Microservices Communication. The basic syntax of
14 min read
Spring Boot Microservices Communication using WebClient with Example
WebClient is an interface illustrating the main entry point for performing web requests. It is also known as the reactive web client which is introduced in Spring 5. This new client is a reactive, non-blocking solution that works over the HTTP/1.1 protocol. We can also say that it is a replacement for the classic RestTemplate. It is a part of sprin
15 min read
Spring Boot Microservices Communication using FeignClient with Example
FeignClient also known as Spring Cloud OpenFeign is a Declarative REST Client in Spring Boot Web Application. But what do you mean by Declarative REST Client? It means we need to specify the client specification as an Interface and Spring Boot will take care of the implementation for us. Writing web services with the help of FeignClient is very eas
15 min read
Article Tags :
Practice Tags :