給你一個類:
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() 方法之後被執行。
提示:
- 盡管輸入中的數字似乎暗示了順序,但是我們并不保證線程在作業系統中的排程順序。
- 你看到的輸入格式主要是為了確定測試的全面性。
示例 1:
輸入:nums = [1,2,3]
輸出:"firstsecondthird"
解釋:
有三個線程會被異步啟動。輸入 [1,2,3] 表示線程 A 将會調用 first() 方法,線程 B 将會調用 second() 方法,線程 C 将會調用 third() 方法。正确的輸出是 "firstsecondthird"。
示例 2:
輸入:nums = [1,3,2]
輸出:"firstsecondthird"
解釋:
輸入 [1,3,2] 表示線程 A 将會調用 first() 方法,線程 B 将會調用 third() 方法,線程 C 将會調用 second() 方法。正确的輸出是 "firstsecondthird"。
- nums 是 [1, 2, 3] 的一組排列
class Foo {
public:
Foo() {
que.push(1);
que.push(2);
que.push(3);
}
void first(function<void()> printFirst) {
// printFirst() outputs "first". Do not change or remove this line.
printFirst();
que.pop();
}
void second(function<void()> printSecond) {
// printSecond() outputs "second". Do not change or remove this line.
while(1)
{
while(que.front()==2)
{
printSecond();
que.pop();
return ;
}
}
}
void third(function<void()> printThird) {
// printThird() outputs "third". Do not change or remove this line.
while(1)
{
while(que.front()==3)
{
printThird();
que.pop();
return ;
}
}
}
private:
queue<int>que;
};