题目:Foo类的三个方法会并发执行,确保first,second,third的执行顺序
解题思路:
1.信号量
每个 acquire() 方法阻塞,直到有一个许可证可以获得然后拿走一个许可证。
每个 release() 方法增加一个许可证,这可能会释放一个阻塞的 acquire() 方法。
class Foo {
private Semaphore seam_first_two = new Semaphore(0); // 同一时间只有0个线程能访问,意味着锁定 private Semaphore seam_two_three = new Semaphore(0); public Foo() { } public void first(Runnable printFirst) throws InterruptedException { // 没有阻塞,直接执行了
printFirst.run();
// 释放一个执行许可seam_first_two seam_first_two.release(); } public void second(Runnable printSecond) throws InterruptedException { // 需要等待seam_first_two释放 seam_first_two.acquire(); printSecond.run();
// 释放一个执行许可seam_two_three seam_two_three.release(); } public void third(Runnable printThird) throws InterruptedException { // 需要等待seam_two_three释放 seam_two_three.acquire(); printThird.run(); } }