其他分享
首页 > 其他分享> > 关于Leetcode的交替打印FooBar,我的答案一直超时

关于Leetcode的交替打印FooBar,我的答案一直超时

作者:互联网

class FooBar {
    private int n;

    public FooBar(int n) {
        this.n = n;
    }

    private volatile boolean fooStarted;
    private final Object lock = new Object();
    public void foo(Runnable printFoo) throws InterruptedException {

        for (int i = 0; i < n; i++) {
            System.out.println("foo " + i);
            synchronized (lock) {
                System.out.println("foo synchronized" + i);
                // printFoo.run() outputs "foo". Do not change or remove this line.
                fooStarted=true;
                printFoo.run();
                lock.notifyAll();
                System.out.println("end notify");
                lock.wait();
                System.out.println("end wait");
                System.out.println("aa");
            }
        }
    }

    public void bar(Runnable printBar) throws InterruptedException {

        for (int i = 0; i < n; i++) {
            System.out.println("bar " + i);
            synchronized (lock) {
                System.out.println("bar synchronized" + i);
                if (!fooStarted) {
                    System.out.println("prepare wait");
                    lock.wait();
                    System.out.println("begin wait");
                }
                // printBar.run() outputs "bar". Do not change or remove this line.
                printBar.run();
                lock.notifyAll();
                System.out.println("bar notify");
/*
                if (i==n-1) {
                    break;
                }
*/
                lock.wait();

                System.out.println("bar wait");
            }
        }
    }
}

起始是因为bar的wait调用之后,这个bar线程一直存活,导致该线程无法结束,引起的Leetcode判定超时。

只需要加上那个if break的代码就行了。

另说一句:这里我对bar的最开始用的是if判定的wait,而不是用while判定的wait,因为我认为没有必要哈。

标签:bar,FooBar,System,wait,lock,println,超时,Leetcode,out
来源: https://www.cnblogs.com/woyujiezhen/p/14494096.html