Donnie

不积跬步无以至千里

CountDownLatch Demo

    import java.util.concurrent.CountDownLatch;
    import java.util.concurrent.TimeUnit;
    
    public class CountDownLatchDemo {
    
        public static void main(String[] args) throws InterruptedException {
    
            //初始化2
            CountDownLatch countDownLatch = new CountDownLatch(2) {
                @Override
                public void await() throws InterruptedException {
                    super.await();
                    System.out.println(Thread.currentThread().getName() + " count down is ok");
                }
            };
    
            Thread t1 = new Thread(()-> {
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() );
                countDownLatch.countDown(); //减1
            }, "t1");
    
            Thread t2 = new Thread(()-> {
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName());
                countDownLatch.countDown(); //减1
            }, "t2");
    
    
            t2.start();
            t1.start();
    
            countDownLatch.await();
        }
    
    }
赞赏支持