Created
February 6, 2017 00:58
-
-
Save tgvdinesh/c41ded4f47a260c2e55f20486e4cd05d to your computer and use it in GitHub Desktop.
Sometimes we need to wait for other threads to finish it’s execution before we can proceed. We can achieve this using Thread join, learn how it works and when we should use it.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.logging.Logger; | |
/** | |
* Thread join | |
* <a href="http://www.journaldev.com/1024/java-thread-join-example">Java Thread Join</a> | |
*/ | |
class ThreadJoin { | |
static Logger logger = Logger.getLogger(App.class.getSimpleName()); | |
public static void main(String[] args) { | |
System.setProperty("java.util.logging.SimpleFormatter.format", | |
"%1$tF %1$tT %4$s %2$s %5$s%6$s%n"); | |
logger.info("Starting"); | |
Thread t1 = new Thread(new MyRunnable(), "t1"); | |
Thread t2 = new Thread(new MyRunnable(), "t2"); | |
Thread t3 = new Thread(new MyRunnable(), "t3"); | |
t1.start(); | |
//start second thread after waiting for 2 seconds or if it's dead | |
try { | |
t1.join(2000); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
t2.start(); | |
//start third thread only when first thread is dead | |
try { | |
t1.join(); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
t3.start(); | |
//let all threads finish execution before finishing main thread | |
try { | |
t1.join(); | |
t2.join(); | |
t3.join(); | |
} catch (InterruptedException e) { | |
// TODO Auto-generated catch block | |
e.printStackTrace(); | |
} | |
logger.info("All threads are dead, exiting main thread"); | |
} | |
} | |
class MyRunnable implements Runnable { | |
@Override | |
public void run() { | |
App.logger.info("Thread started:::" + Thread.currentThread().getName()); | |
try { | |
Thread.sleep(10000); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
App.logger.info("Thread ended:::" + Thread.currentThread().getName()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment