CountDownLatch定义多个线程的使用

CountDownLatch的使用

package com.lezu.springboot.test;

import java.util.concurrent.CountDownLatch;

public class Main {
    /**
     * 需要注意的点:
     * 每个new Therad线程中的代码块用try catch包起来finally
     * 不然一旦报错永远无法countDownLatch.await();
     */
    public static void main(String[] args) {
        CountDownLatch countDownLatch = new CountDownLatch(3);
        new Thread(() -> {
            try {
                int i = 2 / 0; //报错也不回影响最下面的countDownLatch.await();
                System.out.println("------1");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                countDownLatch.countDown();
            }
        }).start();

        new Thread(() -> {
//            int i = 2 / 0; //报错后影响countDownLatch.await();会一直阻塞
            System.out.println("------2");
            countDownLatch.countDown();
        }).start();

        new Thread(() -> {
            System.out.println("------3");
            countDownLatch.countDown();
        }).start();

        try {
            countDownLatch.await(); //永远等待当前的3个线程一直运行完成
//            countDownLatch.await(5L, TimeUnit.SECONDS); //5秒钟之内不管当前的3个线程是否运行完都不在等待
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("运行结束!!");
    }
}

 

posted @ 2022-06-07 13:10  难忘是想起  阅读(0)  评论(0)    收藏  举报  来源