Thread Join Demo : Thread Join « Thread « Java Tutorial






Thread Joinclass TryThread extends Thread {
  public TryThread(String firstName, String secondName, long delay) {
    this.firstName = firstName;
    this.secondName = secondName;
    aWhile = delay;
    setDaemon(true);
  }
  public void run() {
    try {
      while (total < 1000) {
        System.out.print(firstName);
        sleep(aWhile);
        total += aWhile;
        System.out.print(secondName + "\n");
      }
      System.out.print(secondName + " stoped.\n");
    } catch (InterruptedException e) {
      System.out.println(firstName + secondName + e);
    }
  }
  private String firstName;
  private String secondName;
  private long aWhile;
  private long total;
}
public class MainClass {
  public static void main(String[] args) {
    Thread first = new TryThread("A ", "a ", 200L);
    Thread second = new TryThread("B ", "b ", 300L);
    Thread third = new TryThread("C ", "c ", 500L);
    first.start();
    second.start();
    third.start();
    try {
      first.join();
    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}
A B C a 
A b 
B a 
A c 
C a 
A b 
B a 
A b 
B c 
c  stoped.
a 
a  stoped.








10.5.Thread Join
10.5.1.Thread Join Demo
10.5.2.Specify the number of milliseconds to wait for the death of a thread
10.5.3.Wait the for the completion of a thread
10.5.4.Wait for the threads to finish
10.5.5.Using join() to wait for threads to finish.