怎么用CountDownLatch完成LeetCode1114

发布时间:2021-12-27 15:57:33 作者:iii
来源:亿速云 阅读:124

本篇内容主要讲解“怎么用CountDownLatch完成LeetCode1114”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“怎么用CountDownLatch完成LeetCode1114”吧!

1) CountDownLatch初始化之后设置的计数值在被减到0之后就不能被复原了,而Semaphore可以通过release恢复信号/许可的数量,所以CountDownLatch能解决的问题范畴要小于Semaphore。在用到了semaphore.release这种操作的代码里,我们基本是没办法用CountDownLatch替换Semaphore来解决的。CountDownLatch就如一次性的门栓之于大门,门栓被拉开之后,大门的状态只能是‘开’了,我们没有能力再把门关起来。而Semaphore更像是信号灯,我们可以根据需要给出不同的‘红’、‘绿’(release)信号,因此适用的场景可以更复杂。

所以对于LeetCode多线程练习题,只有1114题可以用CountDownLatch来完成。

2) 另外,从允许、禁止这个方向上讲,Semaphore是信号/许可数量大于0时线程可运行(semapher.acquire不阻塞),对于CoundDownLatch来说则是计数值等于0时线程可运行(countDownLatch.await不阻塞)。

用CountDownLatch完成LeetCode 1114:

public class FooByCDL {
   private CountDownLatch cdl2 = new CountDownLatch(1);    private CountDownLatch cdl3 = new CountDownLatch(1);    public FooByCDL() {}
   public void first(Runnable printFirst) throws InterruptedException {        printFirst.run();        cdl2.countDown();    }
   public void second(Runnable printSecond) throws InterruptedException {        cdl2.await();        printSecond.run();        cdl3.countDown();    }
   public void third(Runnable printThird) throws InterruptedException {        cdl3.await();        printThird.run();    }
   public static void main(String[] args) {        FooByCDL foo = new FooByCDL();
       new Thread(() -> {            try {                foo.third(() -> System.out.print("three"));            } catch (InterruptedException ie) { ie.printStackTrace();}        }).start();
       new Thread(() -> {            try {                foo.second(() -> System.out.print("two"));            } catch (InterruptedException ie) { ie.printStackTrace();}        }).start();
       new Thread(() -> {            try {                foo.first(() -> System.out.print("one"));            } catch (InterruptedException ie) { ie.printStackTrace();}        }).start();    }}

到此,相信大家对“怎么用CountDownLatch完成LeetCode1114”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

推荐阅读:
  1. CountDownLatch了解
  2. java使用CountDownLatch等待多线程全部执行完成

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

countdownlatch leetcode

上一篇:Windows 8全新任务管理器与云同步是怎样的

下一篇:Windows 8的DevX指的是什么

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》