美文网首页
CountDownLatch

CountDownLatch

作者: 凉快先生 | 来源:发表于2021-01-06 19:54 被阅读0次

计数器,指定计数器的大小,当执行latch.countDown()后计数器减一,当计数器等于0时才能执行latch.await()之后的语句。

public class Study06 {

    public static void main(String[] args) {

        Thread[] threads =new Thread[100];

        CountDownLatch latch =new CountDownLatch(threads.length);

        for (int i =0; i < threads.length; i++) {

            threads[i] =new Thread(()->{

                int result =0;

                for (int j=0; j<10000; j++){

                    result += j;

                }

                    System.out.println(Thread.currentThread().getName()+result);

                    latch.countDown();

            });

        }

        for (int i=0; i

            threads[i].start();

        }

        try {

              latch.await();

        } catch (InterruptedException e) {

                e.printStackTrace();

        }

        System.out.println("end latch");

    }

}

相关文章

网友评论

      本文标题:CountDownLatch

      本文链接:https://www.haomeiwen.com/subject/xieooktx.html