"Hello, Amigo! I see you're making great strides in learning about threads."

"It wasn't so difficult after all."

That's great! Today you have an easy lesson, and the topic is the join method.

Imagine the following situation: the main thread has created a child thread to perform some task. Time passes, and now the main thread needs the results of the work performed by the child thread. But the child thread hasn't yet finished its work. What should the main thread do?

Good question. What should the main thread do?

"This is what the join method is for. It allows us to make one thread wait while another thread finishes its work:"

Code Description
class Printer implements Runnable
{
private String name;
public Printer(String name)
{
this.name = name;
}
public void run()
{
System.out.println("I’m " + this.name);
}
}
Class that implements the Runnable interface.
public static void main(String[] args)
{
Printer printer1 = new Printer("Nick");
Thread thread1 = new Thread(printer1);
thread1.start();

thread1.join();
}
The main thread creates a child thread – thread1.

Then it starts it by calling thread1.start();

And then it waits for it to complete – thread1.join();

One thread can call the join method on a second thread's Thread object. As a result, the first thread (which called the method) stops its work until the second thread (whose object's join method was called) is finished.

We need to distinguish between two things here: we have a thread (a separate execution environment) and we have a Thread object.

"That's it?"

"Yes."

"But why do we have to create a thread and then immediately wait for it to complete?"

"It might not need to right away. It could be after some time has passed. After starting its first child thread, the main thread can assign many more tasks to other threads (by creating them and calling the start method). Then when it doesn't have any work left, it needs to process the results of the first child thread. Whenever you need to wait for another thread to finish working, you need to call the join method."

"Got it."