4.多线程按序打印

大家好,我是晓星航。今天为大家带来的是 多线程按序打印 相关的讲解!😀

题目简介

image-20240331151031321

image-20240331151040787

题目解答

AtomicInteger原子类方法展示:

image-20240331151640859

image-20240331151717246

image-20240331151540073

题目用到方法如上

代码:

class Foo {

  private AtomicInteger firstJobDone = new AtomicInteger(0);
  private AtomicInteger secondJobDone = new AtomicInteger(0);

  public Foo() {}

  public void first(Runnable printFirst) throws InterruptedException {
    // printFirst.run() outputs "first".
    printFirst.run();
    // mark the first job as done, by increasing its count.
    firstJobDone.incrementAndGet();
  }

  public void second(Runnable printSecond) throws InterruptedException {
    while (firstJobDone.get() != 1) {
      // waiting for the first job to be done.
    }
    // printSecond.run() outputs "second".
    printSecond.run();
    // mark the second as done, by increasing its count.
    secondJobDone.incrementAndGet();
  }

  public void third(Runnable printThird) throws InterruptedException {
    while (secondJobDone.get() != 1) {
      // waiting for the second job to be done.
    }
    // printThird.run() outputs "third".
    printThird.run();
  }
}

image-20240331152953013

借助AtomicInteger类来创建变量firstJobDone和secondJobDone,第一个线程无约束可以直接启动。然后再启动完成后让第一个变量设置增加一个当前值image-20240331153247113
从而使得第二个线程获取到当前值启动
image-20240331153335627
image-20240331153453773
,在第二个线程启动完毕后让第二个变量设置增加一个当前值
image-20240331153519416
从而使得第三个线程获取到secondJobDone的值启动
image-20240331153608768
image-20240331153621502

题目链接

1114. 按序打印 - 力扣(LeetCode)

感谢各位读者的阅读,本文章有任何错误都可以在评论区发表你们的意见,我会对文章进行改正的。如果本文章对你有帮助请动一动你们敏捷的小手点一点赞,你的每一次鼓励都是作者创作的动力哦!😘

相关推荐

  1. 线交替打印

    2024-03-31 19:50:05       119 阅读
  2. C++ 线顺序打印

    2024-03-31 19:50:05       57 阅读
  3. 线轮流打印a,b,c

    2024-03-31 19:50:05       54 阅读
  4. 手撕面试题:线交叉打印ABC

    2024-03-31 19:50:05       45 阅读
  5. 利用线打印出1 2 3

    2024-03-31 19:50:05       25 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-31 19:50:05       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-31 19:50:05       101 阅读
  3. 在Django里面运行非项目文件

    2024-03-31 19:50:05       82 阅读
  4. Python语言-面向对象

    2024-03-31 19:50:05       91 阅读

热门阅读

  1. PTA:7-109 公园门票-zzuli

    2024-03-31 19:50:05       38 阅读
  2. Rust语言教程

    2024-03-31 19:50:05       37 阅读
  3. 代码随想录算法训练营 Day39 动态规划2

    2024-03-31 19:50:05       35 阅读
  4. 作业练习(python)

    2024-03-31 19:50:05       34 阅读
  5. 使用WebRTC实现简单直播

    2024-03-31 19:50:05       39 阅读
  6. stm32入门教程——iic通讯

    2024-03-31 19:50:05       35 阅读
  7. 奇异值分解及MATLAB实现

    2024-03-31 19:50:05       34 阅读
  8. 【Webflux】实现全局返回Long转String

    2024-03-31 19:50:05       38 阅读
  9. 面试中会被问到的GIT问题解答(含答案)

    2024-03-31 19:50:05       33 阅读
  10. 在数据开发项目中使用Hive的场景和风险

    2024-03-31 19:50:05       36 阅读
  11. python基础练习题6

    2024-03-31 19:50:05       39 阅读