Leetcode 的多线程编程真好玩,提交多几次就过了,薛定谔的 AC

2019-07-28 22:14:41 +08:00
 lhx2008

我觉得代码没问题,可能是他判题的机制需要改善一下,不能光看打印啊。。

题目:请设计修改程序,以确保 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();
    }
}
1102 次点击
所在节点    分享发现
1 条回复
lhx2008
2019-07-28 22:28:42 +08:00
想了一下可能确实是我的问题,要 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));
}
}

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/586961

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX