Poison

1115. Print FooBar Alternately

Thread.yield()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class 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;
}
}

}
synchronized
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class 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();
}
}
}

}

注意使用 whilenotifyAll

Reference

1115. Print FooBar Alternately