美文网首页
17.CountDownLatch

17.CountDownLatch

作者: 段段小胖砸 | 来源:发表于2021-10-18 15:32 被阅读0次

    假设一个主线程要等待5个 Worker 线程执行完才能退出,可以使用CountDownLatch来实现

    public static void main(String[] args) throws InterruptedException { 
        CountDownLatch latch = new CountDownLatch(5); 
        new MyThread("线程1", latch).start(); 
        new MyThread("线程2", latch).start();
        new MyThread("线程3", latch).start(); 
        new MyThread("线程4", latch).start(); 
        // new MyThread("线程5", latch).start(); 
        // 当前线程等待 
        latch.await(); 
        System.out.println("程序运行结束"); 
    }
    
    
    
    public void run() { 
        try {
            Thread.sleep(random.nextInt(2000)); 
        } catch (InterruptedException e) { 
            e.printStackTrace(); 
        }
        System.out.println(Thread.currentThread().getName() + "运行结束"); 
        latch.countDown(); 
    }
    

    CountDownLatch原理和Semaphore原理类似,同样是基于AQS,不过没有公平和非公平之分

    继承关系图:


    image.png

    相关文章

      网友评论

          本文标题:17.CountDownLatch

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