**
题目
**
我们提供一个类:
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” 将被输出两次。**
解决方法:
**方法一:Semaphore
acquire() :从信号量获取一个许可,如果无可用许可前将一直阻塞等待
release(): 释放一个许可,多次调用该方法,会使信号量的许可数增加,达到动态扩展的效果,如:初始为1, 调用了两次release,最大许可会改变为2
class FooBar {
private int n;
public FooBar(int n) {
this.n = n;
}
Semaphore foo = new Semaphore(1);
Semaphore bar = new Semaphore(0);
public void foo(Runnable printFoo) throws InterruptedException {
for (int i = 0; i < n; i++) {
foo.acquire();
printFoo.run();
bar.release();
}
}
public void bar(Runnable printBar) throws InterruptedException {
for (int i = 0; i < n; i++) {
bar.acquire();
printBar.run();
foo.release();
}
}
}
方法二:volatile
class FooBar {
private int n;
volatile int flag=0;
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(flag==1){Thread.yield();}
printFoo.run();
flag=1;
}
}
public void bar(Runnable printBar) throws InterruptedException {
for (int i = 0; i < n; i++) {
while(flag==0){Thread.yield();}
// printBar.run() outputs "bar". Do not change or remove this line.
printBar.run();
flag=0;
}}
}
方法三:synchronized(obj){··········}```
其他线程只有等到被锁住的对象obj被释放以后,才可以执行大括号中的内容。
obj的方法:
1.wait()
使当前线程进入到阻塞状态直到其他线程执行notify()/notifyAll()来唤醒。
2.notify()
唤醒在此同步锁对象上等待的单个线程。如果有多个线程都在此同步锁对象上等待,则会任意选择其中某个线程进行唤醒操作。
3.notifyAll()
唤醒同步锁对象上等待的所有线程。
class FooBar {
private int n;
private boolean fooTurn = true;
private Object lock = new Object();
public FooBar(int n) {
this.n = n;
}
public void foo(Runnable printFoo) throws InterruptedException {
for (int i = 0; i < n; i++) {
synchronized(lock) {
if (!fooTurn) lock.wait();
fooTurn = false;
// printFoo.run() outputs "foo". Do not change or remove this line.
printFoo.run();
lock.notifyAll();
}
}
}
public void bar(Runnable printBar) throws InterruptedException {
for (int i = 0; i < n; i++) {
synchronized(lock) {
if (fooTurn) lock.wait();
fooTurn = true;
// printBar.run() outputs "bar". Do not change or remove this line.
printBar.run();
lock.notifyAll();
}
}
}
}