Skip to content

Instantly share code, notes, and snippets.

@codinko
Last active December 19, 2021 13:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codinko/0c8f909f42674b9ef3f36cb4082e4ef3 to your computer and use it in GitHub Desktop.
Save codinko/0c8f909f42674b9ef3f36cb4082e4ef3 to your computer and use it in GitHub Desktop.
(1) // Java program to illustrate join() method in Java
import java.lang.*;
public class JoinDemo implements Runnable {
public void run() {
System.out.println("INSIDE Thread t run() .. Thread t starting.........................................................");
try {
System.out.println("Before sleep");
Thread.sleep(5000);
System.out.println("After sleep");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String args[]) throws Exception {
Thread t = new Thread(new JoinDemo());
t.start();
System.out.println("Thread t IS started... ALIVE ? " + t.isAlive());
// t.join();
System.out.println("Thread t AT END ::******:: " +
t.getName() +
" ALIVE ? " + t.isAlive());
}
}
Output
-------
Thread t IS started... ALIVE ? true
INSIDE Thread t run() .. Thread t starting.........................................................
Before sleep
Thread t AT END ::******:: Thread-0 ALIVE ? true
After sleep
-----------------------------------
(2)Add the t.join(); and re-execute
t.join();
Output
-------
Thread t IS started... ALIVE ? true
INSIDE Thread t run() .. Thread t starting.........................................................
Before sleep
After sleep
Thread t AFTER JOIN ::******:: Thread-0 ALIVE ? false
(3) Add the t.join(milliseconds-after-which-join-will-nullify); and re-execute
t.join(1000);
Output
-------
Thread t IS started... ALIVE ? true
INSIDE Thread t run() .. Thread t starting.........................................................
Before sleep
Thread t AFTER JOIN ::******:: Thread-0 ALIVE ? true
After sleep
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment