CountDownLatch原理和运用

CountDownLatch原理和运用

CountDownLatch概念

CountDownLatch是一个同步辅助工具,允许一个或多个线程等待在其他线程中的操作完成,用来协调多线程之间的同步。CountDownLatch使用计数器实现,计数器初始值为线程数量,每个线程完成任务后,计数器值减一,当计数器的值达到零后,等待的线程就可以恢复执行。

CountDownLatch的用法

import lombok.extern.slf4j.Slf4j;

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

@Slf4j(topic = "c.countDownLatchInstance")
public class CountDownLatchInstance {

    public static void main(String[] args) {
        //初始化计数器值为3
        CountDownLatch countDownLatch = new CountDownLatch(3);
        ExecutorService service = Executors.newFixedThreadPool(4);
        service.submit(()->{
            log.info("begin...");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //计数器的值减一
            countDownLatch.countDown();
            log.info("end... {}", countDownLatch.getCount());
        });
        service.submit(()->{
            log.info("begin...");
            try {
                Thread.sleep(1500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            countDownLatch.countDown();
            log.info("end... {}", countDownLatch.getCount());
        });
        service.submit(()->{
            log.info("begin...");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            countDownLatch.countDown();
            log.info("end... {}", countDownLatch.getCount());
        });
        service.submit(()->{
            try {
                //等待其他线程结束做汇总操作
                log.info("waiting...");
                //等待计数器为零后继续执行
                countDownLatch.await();
                log.info("wait end...");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
    }
}

你可能感兴趣的:(并发编程,java,jvm,开发语言)