天天看點

多線程:CountDownLatch Demo

示例: 多線程等待前置任務完成

package com.yqzl.mybatis.test.thread.demo01;

import java.util.Random;
import java.util.concurrent.CountDownLatch;

/**
* @description:
* @author: YqZhilan
* @date: 2020-07-16
*/
public class CountDownLatchDemo {

    static class PreTaskThread implements Runnable {

        private String task;
        private CountDownLatch countDownLatch;

        public PreTaskThread (String task, CountDownLatch countDownLatch) {
            this.task = task;
            this.countDownLatch = countDownLatch;
        }

        @Override
        public void run() {

            Random random = new Random();
            try {
                Thread.sleep(random.nextInt(1000));
                System.out.println(task + " - 任務完成");
                countDownLatch.countDown();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        public static void main(String[] args) {
            CountDownLatch countDownLatch = new CountDownLatch(3);

            new Thread(()->{
                try {
                    System.out.println("等待加載資料 ... ...");
                    System.out.println(String.format("前面還有%d個前置任務", countDownLatch.getCount()));
                    countDownLatch.await();
                    System.out.println("加載資料完成,現在開始!");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();

            new Thread(new PreTaskThread("加載地圖資料", countDownLatch)).start();
            new Thread(new PreTaskThread("加載人物模型", countDownLatch)).start();
            new Thread(new PreTaskThread("加載背景音樂", countDownLatch)).start();
        }
    }
}
           

傳回結果:

等待加載資料 ... ...
加載背景音樂 - 任務完成
前面還有3個前置任務
加載地圖資料 - 任務完成
加載人物模型 - 任務完成
加載資料完成,現在開始!
           

繼續閱讀