大家好,我是晓星航。今天为大家带来的是 多线程按序打印 相关的讲解!😀
题目简介
题目解答
AtomicInteger原子类方法展示:
题目用到方法如上
代码:
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();
}
}
借助AtomicInteger类来创建变量firstJobDone和secondJobDone,第一个线程无约束可以直接启动。然后再启动完成后让第一个变量设置增加一个当前值
从而使得第二个线程获取到当前值启动
,在第二个线程启动完毕后让第二个变量设置增加一个当前值
从而使得第三个线程获取到secondJobDone的值启动
题目链接
感谢各位读者的阅读,本文章有任何错误都可以在评论区发表你们的意见,我会对文章进行改正的。如果本文章对你有帮助请动一动你们敏捷的小手点一点赞,你的每一次鼓励都是作者创作的动力哦!😘