需要:主线程里启动子线程,需要等子线程里的某个操作完成后主线程才能继续往下走。
final CountDownLatch countDownLatch = new CountDownLatch(2);
for(int i=0;i<2;i++) {
// 服务端启动
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(100);
System.out.println("test1");
Thread.sleep(100);
countDownLatch.countDown();
Thread.sleep(100);
System.out.println("test2");
} catch (Exception e) {
e.printStackTrace();
System.exit(-2);
}
}
}).start();
}
System.out.println("test-main1");
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("test-main2");
结果:
test-main1
test1
test1
test-main2
test2
test2
CountDownLatch是原子操作,await()阻塞直到初始值变为0
只有当两个线程都走完test1时主线程才会继续往下走。