join()
is called completes its execution.
thread.join()
, it waits for the specified thread to finish before continuing its own execution. This ensures sequential execution among threads when needed.
join()
methods in the Thread
class:
public final void join() throws InterruptedException
t.join()
.
InterruptedException
if the waiting thread is interrupted while waiting.
public final void join(long millis) throws InterruptedException
public final void join(long millis, int nanos) throws InterruptedException
join(long millis)
method.
class MyThread extends Thread
{
@Override
public void run()
{
// Child thread prints numbers from 1 to 5
for (int i = 1; i <= 5; i++)
{
System.out.println(getName() + " is running: " + i);
}
}
}
public class JoinDemo
{
public static void main(String[] args) throws InterruptedException
{
System.out.println("Main thread started execution.");
// Main thread creates another thread (child thread)
MyThread t1 = new MyThread();
t1.setName("Child-Thread");
t1.start();
// Main thread waits for child thread to finish
// π Here the MAIN THREAD pauses until Child-Thread completes
t1.join();
// Main thread continues its execution (printing 1 to 5)
for (int i = 1; i <= 5; i++)
{
System.out.println("Main thread is running: " + i);
}
System.out.println("Main thread finished execution.");
}
}
Main thread started execution. Child-Thread is running: 1 Child-Thread is running: 2 Child-Thread is running: 3 Child-Thread is running: 4 Child-Thread is running: 5 Main thread is running: 1 Main thread is running: 2 Main thread is running: 3 Main thread is running: 4 Main thread is running: 5 Main thread finished execution.
Note: The join()
method ensures that the current thread waits until the specified thread completes its execution.
Unlike yield()
, it guarantees sequential execution between threads.
join()
is an instance method of the Thread
class.join()
is called completes its execution.join()
method ensures sequential execution between threads when needed.join()
is called is already finished, the current thread continues immediately.InterruptedException
if the waiting thread is interrupted while waiting.join()
allow waiting for a specified time using join(long millis)
or join(long millis, int nanos)
.yield()
, join()
guarantees that the current thread will wait for the target thread to complete before continuing.
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
Weβre here to make our tutorials better based on your thoughts and suggestions.