Skip to content

Instantly share code, notes, and snippets.

@codinko
Created November 29, 2015 23:07
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/3850c6e7dd898234b50a to your computer and use it in GitHub Desktop.
Save codinko/3850c6e7dd898234b50a to your computer and use it in GitHub Desktop.
Use of Thread Join - say current thread must wait for another thread to terminate its execution[something like Pause]
/*
Output WITHOUT Join [although the mix sequence could vary but inconsistent]
Thread 1 arrived...
Thread 2 arrived...
Thread 1 working on 1...
Thread 2 working on 1...
Thread 1 working on 2...
Thread 2 working on 2...
Thread 2 working on 3...
Thread 2 working on 4...
Thread 2 working on 5...
Thread 2 finished.
Thread 1 working on 3...
Thread 1 working on 4...
Thread 1 working on 5...
Thread 1 finished.
*/
/*
Output WITH Join
Thread 1 arrived...
Thread 1 working on 1...
Thread 1 working on 2...
Thread 1 working on 3...
Thread 1 working on 4...
Thread 1 working on 5...
Thread 1 finished.
Thread 2 arrived...
Thread 2 working on 1...
Thread 2 working on 2...
Thread 2 working on 3...
Thread 2 working on 4...
Thread 2 working on 5...
Thread 2 finished.
*/
public class ThreadJoinDemo {
static Thread t1, t2 = null;
class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " arrived...");
for (int i = 1; i < 6; i++) {
System.out.println(Thread.currentThread().getName() + " working on " + i + "...");
}
System.out.println(Thread.currentThread().getName() + " finished.");
}
}
public static void main(String[] args) {
new ThreadJoinDemo().execute();
}
void execute() {
t1 = new Thread(new MyRunnable(), "Thread 1");
t1.start();
try {
t1.join(); // causes the current thread to pause execution until t1's thread terminates
} catch (InterruptedException e) {
e.printStackTrace();
}
t2 = new Thread(new MyRunnable(), "Thread 2");
t2.start();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment