CountDownLatch

CountDownLatch:直译–倒计数门闩。
可应用于某个任务需要其他多个任务共同完成才能完成的场景。

初始化倒计时数字为3,然后运行3个线程,让latch开始阻塞,根据输出可以看出直到三个线程都运行完,阻塞才会停止,主线程才会退出。

public class CountDownLatchTest {

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(3);
        MyThead thead1=new MyThead(latch,"thead1");
        MyThead thead2=new MyThead(latch,"thead2");
        MyThead thead3=new MyThead(latch,"thead3");
        thead1.start();
        thead2.start();
        thead3.start();
        latch.await();
        System.out.println("Main thread end");
    }

    static class MyThead extends Thread {
        private CountDownLatch latch;
        private String theadName;
        public MyThead(CountDownLatch latch,String theadName){
            this.latch=latch;
            this.theadName=theadName;
        }
        @Override
        public void run() {
            try {
                System.out.println(Thread.currentThread().getName()+"begin");
                Thread.sleep(1000L);
                System.out.println(Thread.currentThread().getName()+"end");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            latch.countDown();//倒计时
        }
    }
}

输出:

Thread-0begin
Thread-1begin
Thread-2begin
Thread-2end
Thread-0end
Thread-1end
Main thread end

将初始化线程数设为4,但是依然只给他三个线程去运行

public class CountDownLatchTest {

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(4);
        MyThead thead1=new MyThead(latch,"thead1");
        MyThead thead2=new MyThead(latch,"thead2");
        MyThead thead3=new MyThead(latch,"thead3");
        thead1.start();
        thead2.start();
        thead3.start();
        latch.await();
        System.out.println("Main thread end");
    }

    static class MyThead extends Thread {
        private CountDownLatch latch;
        private String theadName;
        public MyThead(CountDownLatch latch,String theadName){
            this.latch=latch;
            this.theadName=theadName;
        }
        @Override
        public void run() {
            try {
                System.out.println(Thread.currentThread().getName()+"begin");
                Thread.sleep(1000L);
                System.out.println(Thread.currentThread().getName()+"end");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            latch.countDown();
        }
    }
}

输出:

Thread-0begin
Thread-2begin
Thread-1begin
Thread-0end
Thread-1end
Thread-2end

//由于没有第四个线程执行完,这里开始阻塞
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值