【问题】我们提供一个类:
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 class FooBar{
private int n;
//obj为对象锁
private Object obj;
//count % 2 等于 0 就打印foo,等于1就打印bar
private static int count = 0;
public FooBar(int n) {
this.n = n;
obj = new Object();
}
public void foo(Runnable printFoo) throws InterruptedException {
for(int i = 0; i < n; i++) {
synchronized(obj) {
//count % 2 == 1本应该是打印bar的,所以就休眠,释放锁
if(count % 2 == 1) {
obj.wait();
}
//count % 2 == 0 或者是被唤醒了,就打印foo
printFoo.run();
count++;
//打印完foo,应该去唤醒对面打印bar了
obj.notify();
}
}
}
public void bar(Runnable printBar) throws InterruptedException {
//休眠10毫秒,确保是foo方法先执行
Thread.sleep(10);
for(int i = 0; i < n; i++) {
synchronized(obj) {
if(count % 2 == 0) {
obj.wait();
}
printBar.run();
count++;
obj.notify();
}
}
}
//代码测试
public static void main(String[] args) {
FooBar fb = new FooBar(3);
printFoo foo = new printFoo();
printBar bar = new printBar();
//用匿名内部类创建一个线程打印foo
new Thread() {
public void run() {
try {
fb.foo(foo);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();
//用匿名内部类创建一个线程打印bar
new Thread() {
public void run() {
try {
fb.bar(bar);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();
}
}