Java / Java Multithreading
join() method.
An Instance method of a thread object.
It pauses the current thread execution in which the statement is called until the thread object on which join method is invoked complete its execution.
Consider an example Without using join().
package com.tutorials.threading; public class ThreadJoinExample extends Thread { @Override public void run() { try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); return; } System.out.println("The Thread " + currentThread().getName() + " is completed now."); } public static void main(String[] args) { ThreadJoinExample myThread = new ThreadJoinExample(); myThread.start(); System.out.println(currentThread().getName() + " executes this line and completed now."); } }
Output:
main thread executes this line and completes now.
The Thread Thread-0 is completed now.
The main Thread of this program prints "main thread executes this line and completes now." and completes its execution before the myThread print "The Thread Thread-0 is completed now" and completes its execution.
To have the "main" thread wait for myThread object's thread to complete, we may call myThread.join() from the main Thread.
package com.tutorials.threading; public class ThreadJoinFromMainExample extends Thread { @Override public void run() { try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); return; } System.out.println("The Thread " + currentThread().getName() + " is completed now."); } public static void main(String[] args) throws InterruptedException { ThreadJoinExample myThread = new ThreadJoinExample(); myThread.start(); System.out.println(currentThread().getName() + " is going to wait for myThread to complete."); myThread.join(); System.out .println(currentThread().getName() + " thread executes this line after myThread completed and main exits now."); } }
Output:
main is going to wait for myThread to complete.
The Thread Thread-0 is completed now.
main thread executes this line after myThread completed and main exits now.
More Related questions...