题目描述见 leetcode 114
我们给出了以下解法
synchronized
思路是通过 synchronized 限制对临界区的访问。从而使得对flag变量的访问串行话。
class Foo {
private int flag;
private Object lock;
public Foo() {
flag = 0;
lock = new Object();
}
public void first(Runnable printFirst) throws InterruptedException {
printFirst.run();
synchronized (lock) {
flag = 1;
// sync 块中的语句执行完会释放锁
lock.notifyAll();
}
}
public void second(Runnable printSecond) throws InterruptedException {
for (;;) {
synchronized (lock) {
if (flag == 1) {
printSecond.run();
flag = 2;
lock.notifyAll()