leetcode1114

题目类型:并发

题目:按序打印

描述:请设计修改程序,以确保 second() 方法在 first() 方法之后被执行,third() 方法在 second() 方法之后被执行。

 1 class Foo {
 2     private int t = 0;
 3 
 4     public Foo() {
 5 
 6     }
 7 
 8     public synchronized void first(Runnable printFirst) throws InterruptedException {
 9         while (t != 0) {
10             this.wait();
11         }
12         // printFirst.run() outputs "first". Do not change or remove this line.
13         printFirst.run();
14         t++;
15         this.notifyAll();
16     }
17 
18     public synchronized void second(Runnable printSecond) throws InterruptedException {
19         while (t != 1) {
20             this.wait();
21         }
22         // printSecond.run() outputs "second". Do not change or remove this line.
23         printSecond.run();
24         t++;
25         this.notifyAll();
26     }
27 
28     public synchronized void third(Runnable printThird) throws InterruptedException {
29         while (t != 2) {
30             this.wait();
31         }
32         // printThird.run() outputs "third". Do not change or remove this line.
33         printThird.run();
34         t++;
35         this.notifyAll();
36     }
37 }

思路:使用线程同步。定义变量t,

first()需要在t为0时才能被线程执行,执行后将t自增1,修改为1。

second()需要在t为1时才能被线程执行,执行后将t自增1,修改为2。

third()需要在t为2时才能被线程执行,执行后将t自增1。

原文地址:https://www.cnblogs.com/asenyang/p/14377624.html