浅谈CountDownLatch用法,简单超实用

一、前言

1、countDownLatch是在jdk 1.5 被引入,跟它一起被引入的工具类还有CyclicBarrier、Semaphore、concurrentHashMap和BlockingQueue。

2、存在于java.util.cucurrent包下。

二、概念

countDownLatch这个类使一个线程等待其他线程各自执行完毕后再执行。

是通过一个计数器来实现的,计数器的初始值是线程的数量。每当一个线程执行完毕后,计数器的值就-1,当计数器的值为0时,表示所有线程都执行完毕,然后在闭锁上等待的线程就可以恢复工作了。

三、源码

1、构造函数

package java.util.concurrent;

public class CountDownLatch {
    public CountDownLatch(int count) {
        throw new RuntimeException("Stub!");
    }

    public void await() throws InterruptedException {
        throw new RuntimeException("Stub!");
    }

    public boolean await(long timeout, TimeUnit unit) throws InterruptedException {
        throw new RuntimeException("Stub!");
    }

    public void countDown() {
        throw new RuntimeException("Stub!");
    }

    public long getCount() {
        throw new RuntimeException("Stub!");
    }

    public String toString() {
        throw new RuntimeException("Stub!");
    }
}

我们看它只有一个构造函数,CountDownLatch cdLatch = new CountDownLatch(int count); 这里参数count是一个整数。

2、重要方法

public void await() throws InterruptedException {
        throw new RuntimeException("Stub!");
    }

    public boolean await(long timeout, TimeUnit unit) throws InterruptedException {
        throw new RuntimeException("Stub!");
    }

    public void countDown() {
        throw new RuntimeException("Stub!");
    }

await方法:调用await()方法的线程会被挂起,它会等待直到count值为0才继续执行。

await(long timeout,TImeUnit unit)方法:和await()类似,只不过等待一定的时间后count值还没变为0的话就会继续执行。

countDown方法:将count值减1。

四、代码示例

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        countDownLatch();
    }

    /**
     * 栅栏
     */
    private void countDownLatch() {
        final CountDownLatch latch = new CountDownLatch(3);
        System.out.println("主线程开始执行…… ……");
        //第一个子线程执行
        ExecutorService es1 = Executors.newSingleThreadExecutor();
        es1.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(3000);
                    System.out.println("子线程:" + Thread.currentThread().getName() + "执行");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                latch.countDown();
            }
        });
        es1.shutdown();

        //第二个子线程执行
        ExecutorService es2 = Executors.newSingleThreadExecutor();
        es2.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("子线程:" + Thread.currentThread().getName() + "执行");
                latch.countDown();
            }
        });
        es2.shutdown();

        //第三个子线程执行
        ExecutorService es3 = Executors.newSingleThreadExecutor();
        es3.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("子线程:" + Thread.currentThread().getName() + "执行");
                latch.countDown();
            }
        });
        es3.shutdown();
        System.out.println("等待三个线程执行完毕…… ……");
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("三个子线程都执行完毕,继续执行主线程");


    }
}

输出结果为:

System.out: 主线程开始执行…… ……
System.out: 等待三个线程执行完毕…… ……
System.out: 子线程:pool-1-thread-1执行
System.out: 子线程:pool-2-thread-1执行
System.out: 子线程:pool-3-thread-1执行
System.out: 三个子线程都执行完毕,继续执行主线程

【程序员副业】——功重浩:58商机网(w58net)

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值