java并发学习----CountDownLatch

java并发学习—-CountDownLatch

CountDownLatch实际上是一个计数器,能使一个线程在其他线程执行完之后再执行,它是原子性的,同时只有一个线程去操作它。它是通过一个计数器来实现的,计数器的初始值就是首先需要执行线程的数量,当数量减为零,表示所有的线程均已执行完了,然后再执行之后需要执行的线程。

主要有两个方法,await()和countDown(),其中调用await()方法的线程将一直阻塞等待,直到计数器为0,调用countDown(),计数器会减一,当为0的时候,调用await()方法 的线程才会执行。

下面是一个具体的例子,当启动多个框架的时候,主框架会依赖其他的自框架,只有自框架启动完成了,主框架才能启动,这时候就可以用CountDownLatch

public class SubFramework implements Runnable {
    private String name;
    private CountDownLatch countDownLatch;

    public SubFramework(String name, CountDownLatch countDownLatch) {
        this.name = name;
        this.countDownLatch = countDownLatch;
    }

    @Override
    public void run() {
        System.out.println(name + "正在启动...");
        try {
            TimeUnit.SECONDS.sleep(new Random().nextInt(10));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(name + "启动完成...");
        this.countDownLatch.countDown();
    }

}
public class MainFramework implements Runnable{
    private CountDownLatch countDownLatch;

    public MainFramework(CountDownLatch countDownLatch) {
        this.countDownLatch = countDownLatch;
    }

    @Override
    public void run() {
        System.out.println("依赖框架未启动完成...");
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("依赖框架已启动完成,启动主框架....");
    }
}
public class CountDownlatchDemo {
    public static void main(String[] args){
        ExecutorService executorService= Executors.newCachedThreadPool();
        CountDownLatch countDownLatch=new CountDownLatch(4);
        SubFramework subFramework1=new SubFramework("sub1",countDownLatch);
        SubFramework subFramework2=new SubFramework("sub2",countDownLatch);
        SubFramework subFramework3=new SubFramework("sub3",countDownLatch);
        SubFramework subFramework4=new SubFramework("sub4",countDownLatch);
        MainFramework mainFramework=new MainFramework(countDownLatch);

        executorService.execute(mainFramework);
        executorService.execute(subFramework3);
        executorService.execute(subFramework4);
        executorService.execute(subFramework1);
        executorService.execute(subFramework2);

        executorService.shutdown();
    }
}

输出结果

依赖框架未启动完成…
sub3正在启动…
sub4正在启动…
sub1正在启动…
sub2正在启动…
sub1启动完成…
sub2启动完成…
sub4启动完成…
sub3启动完成…
依赖框架已启动完成,启动主框架….

以上 ,只有子框架先启动了,计数器一直减到0,主框架才会启动。

你可能感兴趣的:(java并发学习)