V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
lhx2008
V2EX  ›  分享发现

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

  •  
  •   lhx2008 · 2019-07-28 22:14:41 +08:00 · 1070 次点击
    这是一个创建于 1725 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

    题目:请设计修改程序,以确保 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();
        }
    }
    
    lhx2008
        1
    lhx2008  
    OP
       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));
    }
    }
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5800 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 02:59 · PVG 10:59 · LAX 19:59 · JFK 22:59
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.