题目类型:并发
题目:交替打印
题目描述:两个不同的线程将会共用一个 FooBar 实例。其中一个线程将会调用 foo() 方法,另一个线程将会调用 bar() 方法。
1 class FooBar { 2 private int n; 3 private boolean tag = true; 4 // tag为true时,输出foo 5 // tag为false时,输出bar 6 7 public FooBar(int n) { 8 this.n = n; 9 } 10 11 public void foo(Runnable printFoo) throws InterruptedException { 12 13 for (int i = 0; i < n; i++) { 14 synchronized (this) { 15 while (!tag) { 16 this.wait(); 17 } 18 // printFoo.run() outputs "foo". Do not change or remove this line. 19 printFoo.run(); 20 tag = false; 21 this.notifyAll(); 22 } 23 } 24 } 25 26 public void bar(Runnable printBar) throws InterruptedException { 27 28 for (int i = 0; i < n; i++) { 29 synchronized (this) { 30 while(tag) { 31 this.wait(); 32 } 33 // printBar.run() outputs "bar". Do not change or remove this line. 34 printBar.run(); 35 tag = true; 36 this.notifyAll(); 37 } 38 } 39 } 40 }
思路:定义变量tag(默认为true),用于线程同步。
foo()方法只有在tag为true时,才能被线程执行,执行后将tag改为false。
bar()方法只有在tag为false时,才能被线程执行,执行后将tag改为true。
tag初始状态为true,因此线程会先调用foo()