JUC
CountDownLatch
countDownLatch
用来进行线程同步协作,等待所有线程完成倒计时。
例子:
public class CountDownLatchTest2 {
public static void main(String[] args) {
CountDownLatch countDownLatch = new CountDownLatch(3);
new Thread(()->{
log.info("begin...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//线程调用countDown()方法,让计数减一
countDownLatch.countDown();
log.info("end...");
}).start();
new Thread(()->{
log.info("begin...");
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
countDownLatch.countDown();
log.info("end...");
}).start();
new Thread(()->{
log.info("begin...");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
countDownLatch.countDown();
log.info("end...");
}).start();
log.info("waiting...");
try {
//主线程调用await()进入阻塞
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
log.info("end...");
}
}
countDownLatch的应用
场景在单机模式下,主线程等待其他线程结束,最后主线程恢复运行
public class CountDownLatchTest {
public static void main(String[] args) {
//模拟游戏加载,等待所有线程都结束,游戏开始
ExecutorService service = Executors.newFixedThreadPool(10);
CountDownLatch countDownLatch = new CountDownLatch(10);
String[] array = new String[10];
Random random = new Random();
for(int j =0;j<10;j++){
int k = j;
service.submit(()->{
for(int i=0;i<=100;i++){
try {
Thread.sleep(random.nextInt(100));
} catch (InterruptedException e) {
e.printStackTrace();
}
array[k] = i+"%";
//小技巧通过 System.out.print + "\r" 覆盖上一次打印
System.out.print("\r"+Arrays.toString(array));
}
countDownLatch.countDown();
});
}
try {
countDownLatch.await();
System.out.println("");
log.info("游戏开始");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}