Created
April 5, 2014 15:40
-
-
Save cassc/9993521 to your computer and use it in GitHub Desktop.
Demonstrate usage of java Thread.join() method
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
package test.another; | |
import java.util.concurrent.TimeUnit; | |
public class TestThreadJoin { | |
public static void main(String[] args) throws InterruptedException { | |
Thread t1 = new JoinedThread("1"); | |
t1.start(); | |
// Thread 2 waits for thread 1 to end | |
Thread t2 = new JoinedThread("2",t1); | |
t2.start(); | |
System.out.println("Main thread ends"); | |
} | |
} | |
class JoinedThread extends Thread{ | |
private String name; | |
private Thread waitFor; | |
public JoinedThread( String name){ | |
this(name,null); | |
} | |
public JoinedThread(String name, Thread waitFor){ | |
this.name=name; | |
this.waitFor=waitFor; | |
} | |
@Override | |
public void run() { | |
try { | |
if(waitFor!=null){ | |
waitFor.join(); | |
} | |
System.out.println(name+" thread running ..."); | |
TimeUnit.SECONDS.sleep(3); | |
} catch (InterruptedException e) { | |
// TODO Auto-generated catch block | |
e.printStackTrace(); | |
} | |
System.out.println(name+" thread ends."); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment