CountDownLatch

作者: 尉昌达 | 来源:发表于2020-07-07 07:46 被阅读0次
    1. 简单介绍CountDownLatch的用法
    public class TestCountDownLatch {
        public static void main(String[] args) {
            usingJoin();
            usingCountDownLatch();
        }
    
        private static void usingCountDownLatch() {
            Thread[] threads = new Thread[100];
            CountDownLatch latch = new CountDownLatch(threads.length);//设置为100
    
            for(int i=0; i<threads.length; i++) {
                threads[i] = new Thread(()->{
                    int result = 0;
                    for(int j=0; j<10000; j++) result += j;
                    latch.countDown(); //每调用一次减一
                });
            }
    
            for (int i = 0; i < threads.length; i++) {
                threads[i].start();
            }
    
            try {
                latch.await(); //这边用来阻塞,当100减为0时,就是当100个线程都运行结束,这边才会继续执行下去
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
    
            System.out.println("end latch");
        }
    
        private static void usingJoin() {
            Thread[] threads = new Thread[100];
    
            for(int i=0; i<threads.length; i++) {
                threads[i] = new Thread(()->{
                    int result = 0;
                    for(int j=0; j<10000; j++) result += j;
                });
            }
    
            for (int i = 0; i < threads.length; i++) {
                threads[i].start();
            }
    
            for (int i = 0; i < threads.length; i++) {
                try {
                    threads[i].join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
    
            System.out.println("end join");
        }
    }
    

    上面意思是,当其他线程执行完到latch -> 0,主线程才会在latch.await() 继续执行下去,不然就会等待。
    也可以用join()来实现。

    相关文章

      网友评论

        本文标题:CountDownLatch

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