我觉得代码没问题,可能是他判题的机制需要改善一下,不能光看打印啊。。
题目:请设计修改程序,以确保 two() 方法在 one() 方法之后被执行,three() 方法在 two() 方法之后被执行。
https://leetcode-cn.com/problems/print-in-order/
这个代码可能提交 10 次会有一次通过 [滑稽]
import java.util.concurrent.atomic.AtomicInteger;
class Foo {
public Foo() {
}
private AtomicInteger counter = new AtomicInteger(0);
public void first(Runnable printFirst) throws InterruptedException {
while (!counter.compareAndSet(0, 1)) ;
printFirst.run();
}
public void second(Runnable printSecond) throws InterruptedException {
while (!counter.compareAndSet(1, 2));
printSecond.run();
}
public void third(Runnable printThird) throws InterruptedException {
while (!counter.compareAndSet(2, 3));
printThird.run();
}
}
1
lhx2008 OP 想了一下可能确实是我的问题,要 CAS 包起来就没问题了
import java.util.concurrent.atomic.AtomicInteger; class Foo { public Foo() { } private AtomicInteger counter = new AtomicInteger(0); public void first(Runnable printFirst) throws InterruptedException { while (!counter.compareAndSet(0, 1)) ; printFirst.run(); while (!counter.compareAndSet(1, 2)) ; } public void second(Runnable printSecond) throws InterruptedException { while (!counter.compareAndSet(2, 3)); printSecond.run(); while (!counter.compareAndSet(3, 4)) ; } public void third(Runnable printThird) throws InterruptedException { while (!counter.compareAndSet(4, 5)); printThird.run(); while (!counter.compareAndSet(5, 6)); } } |