CountDownLatch,它维护一个计数器,等待这个CountDownLatch的线程必须等到计数器为0时才可以继续。 测试代码如下:
public class CountDownLatchTest {
/**
* 启动服务器
*/
public static void startServer() throws Exception {
System.out.println("Server is starting.");
final CountDownLatch latch = new CountDownLatch(1);
new Thread(new Runnable() {
@Override
public void run() {
System.out.println(" Start thread 1");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(" End thread 1");
latch.countDown();
}
}).start();
latch.await();
new Thread(new Runnable() {
@Override
public void run() {
System.out.println(" Start thread 2");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(" End thread 2");
}
}).start();
System.out.println("Server is end!");
}
public static void main(String[] args) throws Exception {
CountDownLatchTest.startServer();
}
}
运行结果如下:
Server is starting.
Start thread 1
End thread 1
Server is end!
Start thread 2
End thread 2
由上分析,程序首先运行Thread1.并
latch.await();
这时候,当前线程将被进出等待状态,直到latch 中的计数器转减少成0为止。 CountDownLatch中提供了
countDown()
来减少计数器。当计数器的减少到0 的时候,当前线程将被唤醒,所以执行Thread2.