Java并发编程CountDownLatch的使用2

时间:2023-02-09 20:48:18

代码部分

import java.util.concurrent.CountDownLatch;

public class CountDownLatchTest {
public static void main(String[] args) {
final CountDownLatch countDown = new CountDownLatch(2);
Thread t1 = new Thread(){
@Override
public void run() {
try {
System.out.println("当前线程t1:初始化完成");
countDown.await();
System.out.println("当前线程t1:继续执行");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Thread t2 = new Thread(){
@Override
public void run() {
try {
System.out.println("当前线程t2:初始化完成");
Thread.sleep(3000);
System.out.println("当前线程t2:通知t1继续执行");
countDown.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Thread t3 = new Thread(){
@Override
public void run() {
try {
System.out.println("当前线程t3:初始化完成");
Thread.sleep(3000);
System.out.println("当前线程t3:通知t1继续执行");
countDown.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
t1.start();
t2.start();
t3.start();
}
}
运行结果

当前线程t1:初始化完成
当前线程t3:初始化完成
当前线程t2:初始化完成
当前线程t2:通知t1继续执行
当前线程t3:通知t1继续执行
当前线程t1:继续执行