首页javathreadJava Thread - 如何启动一个线程,然后启动另一个线程,第一个线程在线程2运行时保持运行

Java Thread - 如何启动一个线程,然后启动另一个线程,第一个线程在线程2运行时保持运行

我们想知道如何启动一个线程,然后启动另一个线程,第一个线程在线程2运行时保持运行。
import java.util.concurrent.CountDownLatch;

public class Main {
  static CountDownLatch cdl;

  public static void main(String... s) {
    cdl = new CountDownLatch(1);
    Thread a = new Thread(() -> {
      System.out.println("started a");
      try {
        Thread.sleep(4000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      cdl.countDown();
      System.out.println("stoped a");
    });
    Thread b = new Thread(() -> {
      System.out.println("started b");
      System.out.println("wait a");
      try {
        cdl.await();
      } catch (Exception e) {
        e.printStackTrace();
      }
      System.out.println("stoped b");
    });
    b.start();
    a.start();
  }
}