Specify the number of milliseconds to wait for the death of a thread : Thread Join « Thread « Java Tutorial






class 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(2000); // Wait up to 2 second for thread1 to die
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
}
B A 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.