法1:volatile
class FooBar {
private int n;
volatile private boolean flag = false;
public FooBar(int n) {
this.n = n;
}
public void foo(Runnable printFoo) throws InterruptedException {
for (int i = 0; i < n; i++) {
while(flag == true){
Thread.yield();
}
// printFoo.run() outputs "foo". Do not change or remove this line.
printFoo.run();
flag = true;
}
}
public void bar(Runnable printBar) throws InterruptedException {
for (int i = 0; i < n; i++) {
while(flag == false){
Thread.yield();
}
// printBar.run() outputs "bar". Do not change or remove this line.
printBar.run();
flag = false;
}
}
}
法2:原子
import java.util.concurrent.atomic.AtomicBoolean;
class FooBar {
private int n;
AtomicBoolean flag = new AtomicBoolean(false);
public FooBar(int n) {
this.n = n;
}
public void foo(Runnable printFoo) throws InterruptedException {
for (int i = 0; i < n; i++) {
while(flag.get() == true){
Thread.yield();
}
// printFoo.run() outputs "foo". Do not change or remove this line.
printFoo.run();
flag.set(true);
}
}
public void bar(Runnable printBar) throws InterruptedException {
for (int i = 0; i < n; i++) {
while(flag.get() == false){
Thread.yield();
}
// printBar.run() outputs "bar". Do not change or remove this line.
printBar.run();
flag.set(false);
}
}
}
法3:信号量
import java.util.concurrent.Semaphore;
class FooBar {
private int n;
private final Semaphore sfoo = new Semaphore(1);
private final Semaphore sbar = new Semaphore(0);
public FooBar(int n) {
this.n = n;
}
public void foo(Runnable printFoo) throws InterruptedException {
for (int i = 0; i < n; i++) {
sfoo.acquire();
// printFoo.run() outputs "foo". Do not change or remove this line.
printFoo.run();
sbar.release();
}
}
public void bar(Runnable printBar) throws InterruptedException {
for (int i = 0; i < n; i++) {
sbar.acquire();
// printBar.run() outputs "bar". Do not change or remove this line.
printBar.run();
sfoo.release();
}
}
}


被折叠的 条评论
为什么被折叠?



