多线程 CountDownLatch

霸气de小男生 提交于 2020-04-06 02:56:02

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * 闭锁
 * https://www.cnblogs.com/takumicx/p/9698867.html
 */
public class CountDownLatchTest {

    private static CountDownLatch countDownLatch;

    public static void main(String[] args) throws InterruptedException {
        int count = 10;
        // 初始化计数器值为10
        countDownLatch = new CountDownLatch(count);
        // 开启10个子线程执行子任务
        for (int i = 0; i < count; i++) {
            Thread thread = new Thread(new CountDownThread(countDownLatch, i));
            thread.start();
        }
        // 主线程等待,直到所有子任务完成
        countDownLatch.await();
        // 模拟主线程执行后续工作
        TimeUnit.SECONDS.sleep(1);
        System.out.println("任务执行完毕!");
    }


    private static class CountDownThread implements Runnable {
        CountDownLatch countDownLatch;
        // 子任务序号
        int taskNum;

        public CountDownThread(CountDownLatch countDownLatch, int taskNum) {
            this.countDownLatch = countDownLatch;
            this.taskNum = taskNum;
        }

        @Override
        public void run() {
            try {
                // 模拟子任务的执行
                TimeUnit.MILLISECONDS.sleep(30);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                // 任务执行完毕,则调用countDown方法使计数器值减少1
                countDownLatch.countDown();
            }
            System.out.println("子任务:" + taskNum + " 执行完毕!");
        }
    }
}

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!