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,因为我认为没有必要哈。