Multithreading JUC package of CountDownLatch

CountDownLatch

Used to control one or more of a plurality of threads waiting threads.

Internal use of a counter, each call countDown () method will make counter value minus 1, when reduced to zero, because those calls await () method will be awakened in the waiting threads.


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

public class CountDownLatchExample {

    public static long a = 0;

    public static void main(String[] args) throws InterruptedException {

        final int threadSize = 1000;

        final CountDownLatch countDownLatch = new CountDownLatch(threadSize);

        AtomicInteger atomicInteger=new AtomicInteger();//原子性类

        ExecutorService executorService = Executors.newCachedThreadPool();

        long start = System.currentTimeMillis();

        for (int i = 0; i < threadSize; i++) {
            executorService.execute(() -> {
//                a++;  这里不是原子性操作,在多线程环境下有问题,使用下面这种操作
                atomicInteger.incrementAndGet();
                countDownLatch.countDown();
            });
        }

//        executorService.execute(()->{
//
//            try {
//                //  countDownLatch 的一个很严重的问题 报错了没有减的话,线程会进入无限等待中
//                int i=1/0;
//            } catch (Exception e) {
//                e.printStackTrace();
//            } finally {
//                countDownLatch.countDown();
//            }
//        });

        long end = System.currentTimeMillis();

        System.out.println(end-start+"\t毫秒的执行时间");

        countDownLatch.await();
        executorService.shutdown();

        System.out.println("value:\t"+atomicInteger);
    }
}

Released four original articles · won praise 1 · views 84

Guess you like

Origin blog.csdn.net/weixin_44329272/article/details/104109930