
Joining thread in java
The Java can use the join()
method to make one thread wait for the completion of another thread. When you call join()
on a thread, the calling thread will pause and wait until the target thread (the thread on which join()
is called) finishes its execution. This is a way to synchronize the execution of threads and ensure that one thread completes its work before another one proceeds. Here’s how you can use the join()
method:
public class JoinExample {
public static void main(String[] args) {
Thread thread1 = new Thread(new MyRunnable("Thread 1"));
Thread thread2 = new Thread(new MyRunnable("Thread 2"));
thread1.start();
thread2.start();
try {
// Wait for thread1 to finish
thread1.join();
System.out.println("Thread 1 has finished.");
// Wait for thread2 to finish
thread2.join();
System.out.println("Thread 2 has finished.");
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Both threads have completed.");
}
static class MyRunnable implements Runnable {
private String name;
MyRunnable(String name) {
this.name = name;
}
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(name + " is running... (Iteration " + i + ")");
try {
Thread.sleep(1000); // Simulate some work
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
In this example, we have two threads (thread1
and thread2
) that run concurrently. We want to make sure that the main thread waits for both thread1
and thread2
to complete before printing the “Both threads have completed.” message. To do this, we use the join()
method for each of the threads.
- After starting
thread1
andthread2
, we callthread1.join()
, which makes the main thread wait forthread1
to complete. - Once
thread1
completes, we print “Thread 1 has finished.” - Then, we call
thread2.join()
, which makes the main thread wait forthread2
to complete. - Once
thread2
completes, we print “Thread 2 has finished.”
This ensures that the main thread doesn’t proceed until both thread1
and thread2
have finished their execution. The output will show the interleaved messages from both threads and the final message indicating that both threads have completed.