【juc】countdownlatch实现游戏进度

目录

        • 一、截图示例
        • 二、代码示例

一、截图示例

在这里插入图片描述

二、代码示例
package com.learning.countdownlatch;

import java.util.Arrays;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author wangyouhui
 * @Description 游戏进度
 **/
public class Learning_02 {
    public static void main(String[] args) {
        System.out.println("游戏进度");
        CountDownLatch countDownLatch = new CountDownLatch(10);
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        Random random = new Random();
        String[] array = new String[10];
        for (int i = 0; i < 10; i++) {
            int a = i;
            executorService.submit(()->{
                for (int j = 0; j <= 100; j++) {
                    try {
                        Thread.sleep(random.nextInt(100));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    array[a] = j + "%";
                    System.out.print("\r" + Arrays.toString(array));
                }
                countDownLatch.countDown();
            });
        }
        // 主线程等待
        try{
            countDownLatch.await();
            System.out.println("\n游戏开始");
        }catch (InterruptedException e){
            e.printStackTrace();
        }
        executorService.shutdown();
    }
}

你可能感兴趣的:(juc,juc)