首页javaconcurrentJava Thread - 如何使用CountDownLatch协调线程

Java Thread - 如何使用CountDownLatch协调线程

我们想知道如何使用CountDownLatch协调线程。
import java.util.concurrent.CountDownLatch;

public class Main {
  CountDownLatch latch = new CountDownLatch(1);
  public void a() {
    new Thread(new Runnable() {
      @Override
      public void run() {
        System.out.println("A: I am going to sleep");
        System.out.println("A: I slept one full day. Feels great.");
        System.out.println("A: Hey B, wake up!");
        try {
          Thread.sleep(1000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        latch.countDown();
      }
    }).start();
  }

  public void b() {
    new Thread(new Runnable() {
      @Override
      public void run() {
        System.out.println("B: I am  going to sleep. A, please wake me up.");
        try {
          latch.await();
        } catch (InterruptedException e) {
        }
        System.out.println("B: Thank you A for waking me up!");
      }
    }).start();
  }

  public static void main(String[] args) {
    Main obj = new Main();
    obj.a();
    obj.b();
  }

}