我们提供了一个类:
public class Foo {
public void first() { print("first"); }
public void second() { print("second"); }
public void third() { print("third"); }
}
三个不同的线程将会共用一个 Foo 实例。
线程 A 将会调用 first() 方法
线程 B 将会调用 second() 方法
线程 C 将会调用 third() 方法
请设计修改程序,以确保 second() 方法在 first() 方法之后被执行,third() 方法在 second() 方法之后被执行。
示例 1:
输入: [1,2,3]
输出: "firstsecondthird"
解释:
有三个线程会被异步启动。
输入 [1,2,3] 表示线程 A 将会调用 first() 方法,线程 B 将会调用 second() 方法,线程 C 将会调用 third() 方法。
正确的输出是 "firstsecondthird"。
示例 2:
输入: [1,3,2]
输出: "firstsecondthird"
解释:
输入 [1,3,2] 表示线程 A 将会调用 first() 方法,线程 B 将会调用 third() 方法,线程 C 将会调用 second() 方法。
正确的输出是 "firstsecondthird"。
提示:
尽管输入中的数字似乎暗示了顺序,但是我们并不保证线程在操作系统中的调度顺序。
你看到的输入格式主要是为了确保测试的全面性。
分析题意,需要保证三个线程的执行顺序,考虑 控制并发流程的工具类:
1、CountDownLatch倒计时门闩,设定一个计数,数量递减到0时,触发操作;
后执行的线程将其计数置1,先执行的线程执行完成后将下一个线程的CountDownLatch计数-1,即执行countDown();
class Foo {
private CountDownLatch two = new CountDownLatch(1);
private CountDownLatch three = new CountDownLatch(1);
public Foo() {}
public void first(Runnable printFirst) throws InterruptedException {
// printFirst.run() outputs "first". Do not change or remove this line.
printFirst.run();
two.countDown(); //two变为0,线程二执行!
}
public void second(Runnable printSecond) throws InterruptedException {
two.await(); //调用await()的线程会被挂起,他会等待直到count为0才继续执行!
// printSecond.run() outputs "second". Do not change or remove this line.
printSecond.run();
three.countDown(); //线程三执行!
//countDownLatch不能重用,不用担心释放问题,这是Cyclicbarrier需要考虑的!
}
public void third(Runnable printThird) throws InterruptedException {
three.await(); //线程三阻塞
// printThird.run() outputs "third". Do not change or remove this line.
printThird.run();
}
}
2、 Semaphore信号量(轻量级CountDownLatch),设定许可证的数量,为0时,进入阻塞状态;
后执行的线程将其许可证数置0使其阻塞,先执行的线程执行完成后将下一个执行线程的许可证+1,即执行release();
class Foo {
private Semaphore two = new Semaphore(0,true);
private Semaphore three = new Semaphore(0,true);
public Foo() {}
public void first(Runnable printFirst) throws InterruptedException {
// printFirst.run() outputs "first". Do not change or remove this line.
printFirst.run();
two.release();
}
public void second(Runnable printSecond) throws InterruptedException {
two.acquire(); //获取two信号量许可证,为0则进入阻塞
// printSecond.run() outputs "second". Do not change or remove this line.
printSecond.run();
three.release(); //释放three信号量许可证
}
public void third(Runnable printThird) throws InterruptedException {
three.acquire();
// printThird.run() outputs "third". Do not change or remove this line.
printThird.run();
}
}
3、CyclicBarrier