User Tools

Site Tools


java:threads:join-wait-for-thread-to-finish

Using join method to wait for a thread to finish in java threads

Demonstrates waiting for the completion of a thread's execution using the join method.

ThreadJoin.java
public class ThreadJoin {
 
    public static void main(String[] args) throws InterruptedException {
        // Creating a new thread
        Thread thread = new Thread(() -> {
            try {
                // Simulating a task that takes one second
                Thread.sleep(1000);
                System.out.println("Thread finished its execution.");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
 
        // Starting the thread
        thread.start();
 
        System.out.println("Waiting for the thread to finish.");
 
        // Waiting for the thread to finish its execution
        thread.join();
 
        System.out.println("Main thread continues after the other thread has finished.");
    }
}

Thread Creation: A new thread is created, which performs a simple task (in this case, sleeping for one second). This simulates a task that takes some time to complete.

Starting the Thread: The thread is started using the start method. This begins its execution.

Using join Method: The join method is called on the created thread. This causes the main thread (from which main is running) to wait until the secondary thread completes its execution.

Continuation of Execution: After the secondary thread completes its task and join returns, the execution of the main program continues.

Purpose: The join method is useful when you need certain tasks executed in separate threads to be completed before continuing execution in the main thread. For example, this might be necessary if the main thread depends on the results produced by other threads.

This method ensures that the main thread does not proceed until the other thread has finished its execution, which can be crucial in scenarios where the subsequent code in the main thread relies on the completion of the separate thread.

java/threads/join-wait-for-thread-to-finish.txt · Last modified: 2024/01/17 02:18 by odefta