Java
threading
multithreading
concurrency
synchronization

How to make a Java thread wait for another thread's output?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

In concurrent programming using Java, there might be scenarios where you need one thread to wait for the output of another thread before it continues execution. This is particularly common in complex applications where tasks are interdependent. This article will delve into the methods available in Java to make one thread wait for another's completion, providing technical explanations and examples along the way.

Java Thread Basics

Before diving into inter-thread communication, it is important to understand some basics of Java threads:

  • Thread: A thread in Java is the smallest unit of processing. Threads can run concurrently.
  • Lifecycle: A thread goes through different states such as New, Runnable, Blocked, Waiting, Timed Waiting, and Terminated.

Techniques for Inter-Thread Communication

There are several ways to make one thread wait for the output of another thread in Java, which include:

  1. Thread Join
  2. Using Shared Objects with Wait and Notify
  3. CountDownLatch

We'll look into each of these methods with examples to illustrate how they function.

1. Thread Join

The join() method is a simple and effective way to make one thread wait for the completion of another. The join() method can be called on a thread to ensure that the current thread waits until the thread it is called upon completes.

Example:

java
1class SampleThread extends Thread {
2    private int result;
3
4    public void run() {
5        // Perform some computation
6        result = 100;
7        System.out.println("Result from other thread: " + result);
8    }
9
10    public int getResult() {
11        return result;
12    }
13}
14
15public class MainThread {
16    public static void main(String[] args) {
17        SampleThread sampleThread = new SampleThread();
18        sampleThread.start();
19
20        try {
21            sampleThread.join(); // main thread waits for sampleThread to finish
22        } catch (InterruptedException e) {
23            e.printStackTrace();
24        }
25
26        // Use the result from sampleThread
27        System.out.println("Processed result: " + sampleThread.getResult());
28    }
29}

2. Using Shared Objects with Wait and Notify

The wait() and notify() methods are part of the Object class and are used for inter-thread communication by synchronizing on a shared object.

Example:

java
1class SharedData {
2    private int result;
3    private volatile boolean isResultReady = false;
4
5    public synchronized void produce() {
6        result = 200;
7        isResultReady = true;
8        notify(); // Signal that the result is ready
9    }
10
11    public synchronized int consume() throws InterruptedException {
12        while (!isResultReady) {
13            wait(); // Wait until the result is ready
14        }
15        return result;
16    }
17}
18
19public class MainThread {
20    public static void main(String[] args) {
21        SharedData sharedData = new SharedData();
22
23        Thread producer = new Thread(() -> sharedData.produce());
24        Thread consumer = new Thread(() -> {
25            try {
26                int result = sharedData.consume();
27                System.out.println("Result from producer: " + result);
28            } catch (InterruptedException e) {
29                e.printStackTrace();
30            }
31        });
32
33        producer.start();
34        consumer.start();
35    }
36}

3. CountDownLatch

CountDownLatch is a synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.

Example:

java
1import java.util.concurrent.CountDownLatch;
2
3public class MainThread {
4    public static void main(String[] args) {
5        CountDownLatch latch = new CountDownLatch(1);
6
7        Runnable worker = () -> {
8            try {
9                System.out.println("Worker thread doing work...");
10                Thread.sleep(2000); // Simulating work
11                System.out.println("Worker thread done!");
12            } catch (InterruptedException e) {
13                e.printStackTrace();
14            }
15            latch.countDown(); // Signal that the worker has completed
16        };
17
18        new Thread(worker).start();
19
20        try {
21            System.out.println("Main thread waiting for worker thread to finish...");
22            latch.await(); // Wait until the latch reaches zero
23            System.out.println("Worker thread has completed. Main thread resumes.");
24        } catch (InterruptedException e) {
25            e.printStackTrace();
26        }
27    }
28}

Summary of Key Methods

Method/ConceptDescriptionUse Case
join()Waits for a thread to dieOne thread waiting for another's completion
wait()/notify()Communication through a shared objectComplex inter-thread communication
CountDownLatchSynchronization aid to wait for operationsMultiple threads completing tasks independently

Conclusion

Knowing how to effectively synchronize threads in Java is essential for writing efficient and correct parallel applications. The tools provided by the Java platform, such as join(), wait()/notify(), and CountDownLatch, provide powerful ways to manage inter-thread dependencies and ensure the controlled execution of concurrent tasks. By understanding how and when to use these mechanisms, you can ensure that your programs are both robust and highly efficient.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.