要求:使用两个线程交叉打印n次"foo"和"bar"
1.FooBar类
定义foo和bar的方法用来控制如何打印字符串。
foo和bar方法接受一个runnable类,prinFoo,和printBar为参数 该类用于在控制台输出一个字符串"foo"或者"bar"。foo和bar方法判断是否满足打印条件,并且执行n次。如果不满足条件,则暂时阻塞。
package ThreadLeetcode;
class FooBar {
private int n;
private volatile boolean finish=false;
public FooBar(int n) {
this.n = n;
}
public void foo(Runnable printFoo) throws InterruptedException {
for (int i = 0; i < n; i++) {
// printFoo.run() outputs "foo". Do not change or remove this line.
while(finish){
Thread.yield();
}
printFoo.run();
finish=true;
}
}
public void bar(Runnable printBar) throws InterruptedException {
for (int i = 0; i &l