题目:
我们提供了一个类:
public class Foo {
public void one() { print(“one”); }
public void two() { print(“two”); }
public void three() { print(“three”); }
}
三个不同的线程将会共用一个 Foo 实例。
线程 A 将会调用 one() 方法
线程 B 将会调用 two() 方法
线程 C 将会调用 three() 方法
请设计修改程序,以确保 two() 方法在 one() 方法之后被执行,three() 方法在 two() 方法之后被执行。
注意:
尽管输入中的数字似乎暗示了顺序,但是我们并不保证线程在操作系统中的调度顺序。
你看到的输入格式主要是为了确保测试的全面性。
思路:
为了保证多线程执行顺序,可以通过设置屏障的方式,two函数等待one函数的屏障,three函数等待two函数的屏障,这里使用volatile保证线程直接读取主存变量,也可以采用CountDownLatch,信号量等方式解决,我的代码如下:
class Foo {
volatile boolean one = false;
volatile boolean two = false;
public Foo() {
}
public void first(Runnable printFirst) throws InterruptedException {
printFirst.run();
one = true;
}
public void second(Runnable printSecond) throws InterruptedException {
while(!one){
;
}
printSecond.run();
two = true;
}
public void third(Runnable printThird) throws InterruptedException {
while(!two){
;
}
printThird.run();
}
}