import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CountDownLatchExample1 {
//volatile 关键字确保多线程环境下的可见性
public volatile static Integer num = 0;
public static String[] res = new String[5];
private static final int threadCount = 5;
public static void main(String[] args) throws InterruptedException {
ExecutorService threadPool = Executors.newFixedThreadPool(5);
final CountDownLatch countDownLatch = new CountDownLatch(threadCount);
Random random = new Random();
for (int i = 0; i < threadCount; i++) {
final int threadnum = i;
threadPool.execute(() -> {
try {
int sleepTime = random.nextInt(401) + 100;
Thread.sleep(sleepTime);
res[num++] = "运动员" + (threadnum + 1) + "消耗的时间为" + sleepTime;
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
countDownLatch.countDown();
}
});
}
countDownLatch.await();
threadPool.shutdown();
for (String re : res) {
System.out.println(re);
}
}
}
await()
用来等待计数归零
countDown
()
用来让计数减一