使用Java标准的等待唤醒通知机制,等待唤醒通知方法模板
synchronized(lock){
while(条件不满足) lock.wait();
执行操作
改变条件
lock.notifyAll();
}
class FooBar {
private int n;
private boolean fooTurn = true;
private Object lock = new Object();
public FooBar(int n) {
this.n = n;
}
public void foo(Runnable printFoo) throws InterruptedException {
for(int i=0;i<n;i++){
synchronized(lock){
while(!fooTurn) lock.wait();
printFoo.run();
fooTurn = false;
lock.notifyAll();
}
}
}
public void bar(Runnable printBar) throws InterruptedException {
for (int i = 0; i < n; i++) {
synchronized(lock){
while(fooTurn) lock.wait();
printBar.run();
fooTurn = true;
lock.notifyAll();
}
}
}
}