たCountDownLatchのマルチスレッドJUCパッケージ

たCountDownLatch

スレッドを待機中のスレッドのうちの一つまたは複数を制御するために使用します。

カウンタの内部で使用ゼロに減少するとき、それらのコールが待つ()メソッドは、待機スレッドに覚醒されるため、各コールカウントダウン()メソッドは、カウンタ値マイナス1を行います。


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);
    }
}

リリース元の4件の記事 ウォンの賞賛1 ビュー84

おすすめ

転載: blog.csdn.net/weixin_44329272/article/details/104109930