Java suspends the current thread using the join method

  • 2020-06-19 10:24:19
  • OfStack

The join method of the target thread suspends the current thread until the current thread completes (returned from the run() method), for your reference, the details are as follows

Java code:


package Threads;

import java.io.IOException;

/**
 * Created by Frank
 */
public class Join {
 public static void main(String[] args) {
  Thread t = new Thread() {
   public void run() {
    System.out.println("Reading");
    try {
     System.in.read();
    } catch (IOException e) {
     System.err.println(e);
    }
    System.out.println("Thread finished.");
   }
  };
  System.out.println("Starting");
  t.start();
  System.out.println("Joining");
  try {
   t.join();
  } catch (InterruptedException e) {
   //  Shouldn't happen 
   System.err.println("Who dares interrupt my sleep??");
  }
  System.err.println("Main Finished");
 }
}

Related articles: