题目链接:点击打开链接
题目大意:略。
解题思路:略。
相关企业
- 爱奇艺
- 微软(Microsoft)
AC 代码
// 解决方案(1)
class Foo {
public Foo() {
}
volatile int count=1;
public void first(Runnable printFirst) throws InterruptedException {
printFirst.run();
count++;
}
public void second(Runnable printSecond) throws InterruptedException {
while (count!=2);
printSecond.run();
count++;
}
public void third(Runnable printThird) throws InterruptedException {
while (count!=3);
printThird.run();
}
}
// 解决方案(2)
class Foo {
private boolean firstFinished;
private boolean secondFinished;
private Object lock = new Object();
public Foo() {
}
public void first(Runnable printFirst) throws InterruptedException {
synchronized (lock) {
// printFirst.run() outputs "first". Do not change or remove this line.
printFirst.run();
firstFinished = true;
lock.notifyAll();
}
}
public void second(Runnable printSecond) throws InterruptedException {
synchronized (lock) {
while (!firstFinished) {
lock.wait();
}
// printSecond.run() outputs "second". Do not change or remove this line.
printSecond.run();
secondFinished = true;
lock.notifyAll();
}
}
public void third(Runnable printThird) throws InterruptedException {
synchronized (lock) {
while (!secondFinished) {
lock.wait();
}
// printThird.run() outputs "third". Do not change or remove this line.
printThird.run();
}
}
}