CountDownLatch 相见恨晚

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012153184/article/details/52790183

CountDownLatch 相见恨晚

之前一直纠结android 子线程和主线程的数据同步的问题 ,偶然间看到了鸿洋的博客介绍了 CountDownLatch 这个类 才知道原来java已经帮我们内置了一个同步辅助类。
这个类的方法不多
这里写图片描述

CountDowmLatch是一种灵活的闭锁实现,包含一个计数器,该计算器初始化为一个正数,表示需要等待事件的数量。countDown方法递减计数器,表示有一个事件发生,而await方法等待计数器到达0,表示所有需要等待的事情都已经完成。

下面来看代码

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

        run1();
        run2();
        run3();
        try {
            latch.await();
            System.out.println("结束");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

    public static void run1() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                long  a=0;
                for (int i = 0; i < 1000000003; i++) {
                    a+=i;
                }

                    System.out.println("run1 运行完毕");
                    latch.countDown();
            }
        }).start();
    }
    public static void run3() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                long  a=0;
                for (int i = 0; i < 106000002; i++) {
                    a+=i;
                }
                System.out.println("run3 运行完毕");
                latch.countDown();
            }
        }).start();
    }
    public static void run2() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                long  a=0;
                for (int i = 0; i < 1000000000; i++) {
                    a+=i;
                }
                System.out.println("run2 运行完毕");
                latch.countDown();
            }
        }).start();
    }
}

运行结果

run3 运行完毕
run1 运行完毕
run2 运行完毕
结束

文章借鉴 于张鸿洋的博客http://blog.csdn.net/lmj623565791/article/details/26626391

猜你喜欢

转载自blog.csdn.net/u012153184/article/details/52790183