1115. Print FooBar Alternately 发表于 2022-02-05 Thread.yield()1234567891011121314151617181920212223242526272829303132333435class FooBar { private int n; private volatile boolean shouldPrintFoo = true; public FooBar(int n) { this.n = n; } public void foo(Runnable printFoo) throws InterruptedException { for (int i = 0; i < n; i++) { while (!shouldPrintFoo) { Thread.yield(); } // printFoo.run() outputs "foo". Do not change or remove this line. printFoo.run(); shouldPrintFoo = false; } } public void bar(Runnable printBar) throws InterruptedException { for (int i = 0; i < n; i++) { while (shouldPrintFoo) { Thread.yield(); } // printBar.run() outputs "bar". Do not change or remove this line. printBar.run(); shouldPrintFoo = true; } }} synchronized123456789101112131415161718192021222324252627282930313233343536373839404142class FooBar { private int n; private final Object lock = new Object(); private boolean shouldPrintFoo = true; public FooBar(int n) { this.n = n; } public void foo(Runnable printFoo) throws InterruptedException { for (int i = 0; i < n; i++) { synchronized (lock) { while (!shouldPrintFoo) { lock.wait(); } // printFoo.run() outputs "foo". Do not change or remove this line. printFoo.run(); shouldPrintFoo = false; lock.notifyAll(); } } } public void bar(Runnable printBar) throws InterruptedException { for (int i = 0; i < n; i++) { synchronized (lock) { while (shouldPrintFoo) { lock.wait(); } // printBar.run() outputs "bar". Do not change or remove this line. printBar.run(); shouldPrintFoo = true; lock.notifyAll(); } } }} 注意使用 while 与 notifyAll。 Reference1115. Print FooBar Alternately