CountDownLatch为一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待。
方法说明:
await() 使当前线程在锁存器倒计数至零之前一直等待,除非线程被中断
countDown() 递减锁存器的计数,如果计数到达零,则释放所有等待的线程
getCount() 返回当前计数
相关实例说明:
import org.springframework.stereotype.Component;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@Component
public class CountDownLatchTest {
public static void main(String[] args) throws InterruptedException {
final CountDownLatch begin = new CountDownLatch(1);
final CountDownLatch end = new CountDownLatch(10);
ExecutorService es = Executors.newFixedThreadPool(10);
for (int i = 0; i < 10; i++) {
final int index = i + 1;
es.submit(new Runnable() {
public void run() {
try {
begin.await(); // 等待指令
int s = (int)(Math.random() * 1000);
Thread.sleep(s);
System.out.println(String.format("No.%d到达,花费时间:%d毫秒!", index, s));
end.countDown();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
System.out.println("各就位,预备跑!");
begin.countDown();
end.await();
System.out.println("Game over!");
es.shutdown();
}
}