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.
Dogecoin
! Earn free bitcoins up to $250 now by signing up.
Earn bitcoins upto $250 (free), invest in other Cryptocurrencies when you signup with blockfi.
Use the referral link: Signup now and earn!
Using BlockFi, don't just buy crypto - start earning on it. Open an interest account with up to 8.6% APY, trade currencies, or borrow money without selling your assets.
Join CoinBase
! We'll both receive $10 in free Bitcoin when they buy or sell their first $100 on Coinbase! Available in India also.
Use the referral Join coinbase!
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull
! Receive free stock by signing up using the link: Webull signup.
More Related questions...