线程协同——juc的cdl

使用CountDownLatch模拟5V5游戏玩家从加载到游戏开始过程

玩家进度加载监测线程等10位玩家(10条线程)都加载完毕(latch(10)),游戏主线程等待玩家监测线程执行完毕(latch(1))。所以使用了2个CountDownLatch,12条线程实现该效果。

目录

效果动图

源码


 

效果动图

22f91e3fa1bc4a6899dd259de9e4b0b3.gif

 

源码

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();
		
		
	}
}

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

bitDesigner

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值