java Thread. join of usage

  • 2020-06-19 10:18:50
  • OfStack

Thread. join() in java

If a thread A executes an ES7en.join () statement, this means that the current thread A waits for the thread thread to terminate before returning from thread.join ().


import java.util.concurrent.TimeUnit;

/**
 * 6-13
 */
public class Join {
 public static void main(String[] args) throws Exception {
  Thread previous = Thread.currentThread();
  for (int i = 0; i < 10; i++) {
   //  Before each thread is owned 1 A reference to a thread that needs to wait before 1 The thread terminates before it can return from the wait 
   Thread thread = new Thread(new Domino(previous), String.valueOf(i));
   thread.start();
   previous = thread;
  }

  TimeUnit.SECONDS.sleep(5);
  System.out.println(Thread.currentThread().getName() + " terminate.");
 }

 static class Domino implements Runnable {
  private Thread thread;

  public Domino(Thread thread) {
   this.thread = thread;
  }

  public void run() {
   try {
    thread.join();
   } catch (InterruptedException e) {
   }
   System.out.println(Thread.currentThread().getName() + " terminate.");
  }
 }
}

Execution Results:


main terminate.
0 terminate.
1 terminate.
2 terminate.
3 terminate.
4 terminate.
5 terminate.
6 terminate.
7 terminate.
8 terminate.
9 terminate.
 


Related articles: