代码部分
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:继续执行