模拟游戏开始

2020-11-17 / 0 评论 / 41 阅读 / 正在检测是否收录...
 public static void main(String[] args) throws InterruptedException, BrokenBarrierException {
        Monitor monitor = new Monitor();
        monitor.start();
        Random random = new Random();
        CyclicBarrier cbar = new CyclicBarrier(10);  //够五个同时执行
        CountDownLatch cdl = new CountDownLatch(10);
        for (int i = 0; i < 10; i++) {
            int i1 = random.nextInt(5);
            Thread.sleep(i1*1000);
            System.out.println("准备创建" + (i + 1) + "个线程");
            ClientThread ct = new ClientThread(cbar,cdl);
            ct.start();
        }
        cdl.await();
        System.out.println(Thread.currentThread().getName() + "游戏开始");
    }
public class ClientThread extends  Thread{

    CountDownLatch cdl ;
    CyclicBarrier cbar ;
    Random random;

    public ClientThread(CyclicBarrier cbar,CountDownLatch cdl){
        this.cbar = cbar;
        this.cdl = cdl;
        random = new Random();
    }
    @Override
    public void run() {
        try {
            System.out.println(Thread.currentThread().getName() + " : 号客户端开始排队");
            this.cbar.await();
            System.out.println(Thread.currentThread().getName() + " : 号客户端准备就绪");
            int i = random.nextInt(10);
            Thread.sleep(i * 1000);
            this.cdl.countDown();
            this.cdl.await();
            System.out.println(Thread.currentThread().getName() + " 游戏开始");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (BrokenBarrierException e) {
            e.printStackTrace();
        }

    }
}
public class Monitor extends  Thread{

    @Override
    public void run() {
        int i = 1;
        while (true){
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(i++);
        }
    }
}
本文共 38 个字数,平均阅读时长 ≈ 1分钟
0

打赏

海报

正在生成.....

评论 (0)

取消