Junior — Middle
What is the role of the join() method in the Thread class and why is it used in multithreaded programming?
sobes.tech AI
Answer from AI
The join() method in the Thread class is used to make the current thread wait for the completion of another thread on which this method is called. This allows synchronizing thread execution: the main thread can pause and wait until the child thread completes its task.
For example, if you have a thread that performs a long operation and you want the main thread to continue only after its completion, you call join() on that thread.
Example:
Thread t = new Thread(() -> {
// Long operation
System.out.println("Thread started working");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread finished working");
});
t.start();
try {
t.join(); // Wait for thread t to finish
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Main thread continued after t finished");
Thus, join() helps avoid data inconsistency issues and ensures the correct order of execution in a multithreaded application.