为什么要用CountDownLatch?《十三》

版权声明:本文为HCG原创文章,未经博主允许不得转载。请联系[email protected] https://blog.csdn.net/qq_39455116/article/details/87101426

CountDownLatch并发类的用法

CountDownLatch类位于java.util.concurrent包下,利用它可以实现类似计数器的功能。

比如有一个任务A,它要等待其他4个任务执行完毕之后才能执行,此时就可以利用CountDownLatch来实现这种功能了。

比如下面的代码是让额外的线程和循环里面的线程都执行完毕后才最后打印
System.out.println("10个线程已执行完毕");

package duoxiancheng.bao;

import java.util.concurrent.CountDownLatch;

public class TestCountDownLatch {
    final CountDownLatch latch = new CountDownLatch(11);
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            System.out.println("线程" + Thread.currentThread().getId() + "额外的订单");
            latch.countDown();

        }
    });

    public void test() {
        thread.start();
        for (int i = 0; i < 10; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {

                    System.out.println("线程" + Thread.currentThread().getId() + "..........start");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("线程" + Thread.currentThread().getId() + ".........end...");
                    latch.countDown();
                }
            }).start();
        }


        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("10个线程已执行完毕");
    }

    public static void main(String[] args) {
        TestCountDownLatch c = new TestCountDownLatch();
        c.test();
    }
}

输出结果:

线程12额外的订单
线程13..........start
线程14..........start
线程15..........start
线程16..........start
线程17..........start
线程18..........start
线程19..........start
线程20..........start
线程21..........start
线程22..........start
线程13.........end...
线程19.........end...
线程17.........end...
线程16.........end...
线程22.........end...
线程18.........end...
线程15.........end...
线程14.........end...
线程21.........end...
线程20.........end...
10个线程已执行完毕

为什么要用CountDownLatch ?

1. 其实CountDownLatch实现的功能无非就是等所有的线程执行完毕后执行另一个事情,
	那为什么非要用它呢?
2.  join() 方法也可以实现类似功能,为什么不用呢?
3. 因为:如果只有两三个线程还好,如果数量过多,那得写多少join啊
	而且提前结束任务还得捕获InterruptException异常,繁琐...
4. 线程之间通信  wait/notify ,然后进入synchronized同步代码块,检查计数器不为0 ,然后调用wait()方法
	直到为0,则用notifyAll唤醒等待的最后线程
5. 为什么不用notify呢?
	因为会有大量synchronized同步块,还可以出现假唤醒

猜你喜欢

转载自blog.csdn.net/qq_39455116/article/details/87101426