死磕并发之CountDownLatch的使用

  • CountDownLatch和join的作用类似。

join

Thread.join()方法使线程等待,待线程退出时,调用Thread.join()的主线程会被唤醒,从而执行后续操作。当处于线程池的状态下,线程不会退出,join就会一直执行不到。

  • 非线程池如下示例,会先输出“Child thread running”,然后输出 “执行结束”
public class ThreadJoinDemo {

    private static class ThreadDemo extends Thread {
        @Override
        public void run() {
            try {
                Thread.sleep(1000);
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("Child thread running");
        }
    }

    public static void main(String[] args) throws Exception {
        ThreadDemo threadDemo = new ThreadDemo();
        Thread thread = new Thread(threadDemo);
        thread.start();
        thread.join();
        System.out.println("执行结束");
    }
}
  • 线程池如下示例,会先输出“执行结束”,然后输出 “Child thread running”
public class ThreadJoinDemo {

    private static class ThreadDemo extends Thread {
        @Override
        public void run() {
            try{
                Thread.sleep(1000);
            }catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("Child thread running");
        }
    }

    public static void main(String[] args)throws  Exception {

        ExecutorService executorService = Executors.newFixedThreadPool(1);
        ThreadDemo threadDemo  =  new ThreadDemo();
        executorService.execute(threadDemo);
        threadDemo.join();
        System.out.println("执行结束");
    }

CountDownLatch

countDownLatch方法

    //构造函数 count为计数器
    public CountDownLatch(int count) {
        if (count < 0) throw new IllegalArgumentException("count < 0");
        this.sync = new Sync(count);
    }
    
  //调用await()方法的线程会被挂起,它会等待直到count值为0才继续执行
   public void await() throws InterruptedException {
        sync.acquireSharedInterruptibly(1);
    }
    
  //和await()类似,只不过等待一定的时间后count值还没变为0的话就会继续执行
  public boolean await(long timeout, TimeUnit unit)
        throws InterruptedException {
        return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
    } 
    
  //将count值减1
  public void countDown() {
        sync.releaseShared(1);
    }

CountDownLatch即可解决上述join问题。 如下示例,会优先输出 Child thread running,然后输出 “主线程执行结束”

public class CountDownLatchDemo {

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(1);

        Executor executor = Executors.newFixedThreadPool(1);

        executor.execute(new Runnable() {
            @Override
            public void run() {

                try{
                    Thread.sleep(1000);
                }catch (Exception e) {
                    e.printStackTrace();
                }
                System.out.println("Child thread running");
                countDownLatch.countDown();
            }
        });

        countDownLatch.await();

        System.out.println("主线程线程执行结束");

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值