前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >leetcode多线程之按序打印

leetcode多线程之按序打印

原创
作者头像
code4it
修改2020-09-07 10:31:07
4710
修改2020-09-07 10:31:07
举报
文章被收录于专栏:码匠的流水账

本文主要记录一下leetcode多线程之按序打印

题目

代码语言:javascript
复制
我们提供了一个类:
​
public class Foo {
  public void first() { print("first"); }
  public void second() { print("second"); }
  public void third() { print("third"); }
}
​
三个不同的线程将会共用一个 Foo 实例。
​
    线程 A 将会调用 first() 方法
    线程 B 将会调用 second() 方法
    线程 C 将会调用 third() 方法
​
请设计修改程序,以确保 second() 方法在 first() 方法之后被执行,third() 方法在 second() 方法之后被执行。
​
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/print-in-order
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题解

使用juc包的CountDownLatch

代码语言:javascript
复制
class Foo {
​
    CountDownLatch second = new CountDownLatch(1);
    CountDownLatch third = new CountDownLatch(1);
​
    public Foo() {
        
    }
​
    public void first(Runnable printFirst) throws InterruptedException {
        printFirst.run();
        second.countDown();
        
    }
​
    public void second(Runnable printSecond) throws InterruptedException {
        second.await();
        printSecond.run();
        third.countDown();
    }
​
    public void third(Runnable printThird) throws InterruptedException {
        third.await();
        printThird.run();
    }
}

小结

这里是固定要按first先执行,而后second,再third方法,这里使用了CountDownLatch,比起object的wait notify之类用起来简单一点

doc

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目
  • 题解
  • 小结
  • doc
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档