leetcode 1114题:按序打印
给你一个类:
public class Foo {
public void first() { print("first"); }
public void second() { print("second"); }
public void third() { print("third"); }
}
三个不同的线程 A、B、C 将会共用一个 Foo 实例。
线程 A 将会调用 first() 方法
线程 B 将会调用 second() 方法
线程 C 将会调用 third() 方法
请设计修改程序,以确保 second() 方法在 first() 方法之后被执行,third() 方法在 second() 方法之后被执行
根据题意可以设置两把锁, first 不受限制,second 会受一把锁的限制,而 second 受mtx1,mtx2 锁的限制;
首先创建对象时构造函数会设置两个锁,first 执行完毕以后,为了让 second 执行,结束执行前会将mtx1 锁解开,让 second 执行,second 执行时再将mtx1锁上,避免 third 比自己先执行,执行结束以后再将 mtx1 与 mtx2 解开,让 third 执行。
class Foo {
public:
mutex mtx1,mtx2;
Foo() {
mtx1.lock();
mtx2.lock();
}
void first(function<void()> printFirst) {
// printFirst() outputs "first". Do not change or remove this line.
//mtx.lock();
printFirst();
mtx1.unlock();
}
void second(function<void()> printSecond) {
// printSecond() outputs "second". Do not change or remove this line.
mtx1.lock();
printSecond();
mtx1.unlock();
mtx2.unlock();
}
void third(function<void()> printThird) {
// printThird() outputs "third". Do not change or remove this line.
mtx2.lock();
printThird();
mtx2.unlock();
}
};