使用CountDownLatch模拟5V5游戏玩家从加载到游戏开始过程
玩家进度加载监测线程等10位玩家(10条线程)都加载完毕(latch(10)),游戏主线程等待玩家监测线程执行完毕(latch(1))。所以使用了2个CountDownLatch,12条线程实现该效果。
目录
效果动图
源码
package psn.concurrent;
import org.apache.log4j.Logger;
import java.util.Arrays;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
/**
* 玩家线程加载完毕——》监测线程执行完毕——》主线程开始
* on 2023/3/18 18:43
*/
public class TestCountdownLatch{
private static final Logger log = Logger.getLogger(TestCountdownLatch.class);
public static void main(String[] args) throws InterruptedException{
t();
}
public static void t(){
String[] ps = new String[10];
CountDownLatch latch = new CountDownLatch(10);
CountDownLatch latch1 = new CountDownLatch(1);
Random random = new Random();
for(int i = 0;i < 10;i++){
int k = i;
new Thread(()->{
for(int j = 0;j <= 100;j++){
try{
ps[k] = Thread.currentThread().getName() + "-" + j + "%";
System.out.print("\r各玩家加载进度 ===> " + Arrays.toString(ps));
Thread.sleep(random.nextInt(300));
}catch(InterruptedException e){
e.printStackTrace();
}
}
latch.countDown();
}, "玩家" + i).start();
}
new Thread(()->{
try{
latch.await();
System.out.println();
log.debug("所有玩家加载完毕");
latch1.countDown();
}catch(InterruptedException e){
e.printStackTrace();
}
}, "玩家进度加载监测线程").start();
new Thread(()->{
try{
latch1.await();
log.debug("开始对局");
log.debug("对局中......");
Thread.sleep(random.nextInt(10*1000));
log.debug("对局结束");
}catch(InterruptedException e){
e.printStackTrace();
}
}, "游戏主线程").start();
}
}