交替打印FooBar
我们提供一个类:
class FooBar {
public void foo() {
for (int i = 0; i < n; i++) {
print("foo");
}
}
public void bar() {
for (int i = 0; i < n; i++) {
print("bar");
}
}
}
两个不同的线程将会共用一个 FooBar 实例。其中一个线程将会调用 foo() 方法,另一个线程将会调用 bar() 方法。
请设计修改程序,以确保 “foobar” 被输出 n 次。
示例 1:
输入: n = 1
输出: “foobar”
解释: 这里有两个线程被异步启动。其中一个调用 foo() 方法, 另一个调用 bar() 方法,“foobar” 将被输出一次。
示例 2:
输入: n = 2
输出: “foobarfoobar”
解释: “foobar” 将被输出两次。
代码
public static void main(String[] args) throws InterruptedException {
ReentrantLock lock = new ReentrantLock();
Condition condition1 = lock.newCondition();
Condition condition2 = lock.newCondition();
FooBar fooBar = new FooBar(lock, condition1, condition2, 100);
new Thread(fooBar::foo).start();
new Thread(fooBar::bar).start();
Thread.sleep(30000L);
}
static class FooBar {
private int n;
ReentrantLock lock;
Condition condition1;
Condition condition2;
private int a = 1;
public FooBar(ReentrantLock lock, Condition condition1, Condition condition2, int n) {
this.lock = lock;
this.condition1 = condition1;
this.condition2 = condition2;
this.n = n;
}
public void foo() {
for (int i = 0; i < n; i++) {
lock.lock();
try {
if (a != 1) {
try {
condition1.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
print("foo");
a++;
condition2.signal();
} catch (Exception e) {
lock.unlock();
}
}
}
public void bar() {
for (int i = 0; i < n; i++) {
try {
lock.lock();
if (a != 2) {
try {
condition2.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
print("bar");
a++;
condition1.signal();
} catch (Exception e) {
lock.unlock();
}
}
}
}