Lc-1115

Lc 1115.交替打印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 次。

class FooBar {

private int n;

private boolean isFooTurn = true;

private Object obj = new Object();

public FooBar(int n) {
this.n = n;
}

public void foo(Runnable printFoo) throws InterruptedException {
for (int i = 0; i < n; i++) {
synchronized (obj){
if (!isFooTurn){
obj.wait();
}
// printFoo.run() outputs "foo". Do not change or remove this line.
printFoo.run();
isFooTurn = false;
obj.notifyAll();
}
}
}

public void bar(Runnable printBar) throws InterruptedException {
for (int i = 0; i < n; i++) {
synchronized (obj){
if (isFooTurn){
obj.wait();
}
// printBar.run() outputs "bar". Do not change or remove this line.
printBar.run();
isFooTurn = true;
obj.notifyAll();
}
}
}
}

优化

class FooBar {
private int n;

private final Lock lock = new ReentrantLock();
private boolean allowedAProcess = true;
private final Condition conditionA = lock.newCondition();
private final Condition conditionB = lock.newCondition();

public FooBar(int n) {
this.n = n;
}


public void foo(Runnable printFoo) throws InterruptedException {
for (int i = 0; i < n; i++) {
lock.lock();
try {
while (!allowedAProcess) {
conditionA.await();
}
// printFoo.run() outputs "foo". Do not change or remove this line.
printFoo.run();
allowedAProcess = false;
conditionB.signalAll();
} finally {
lock.unlock();
}
}
}

public void bar(Runnable printBar) throws InterruptedException {
for (int i = 0; i < n; i++) {
lock.lock();
try {
while (allowedAProcess) {
conditionB.await();
}
// printBar.run() outputs "bar". Do not change or remove this line.
printBar.run();

allowedAProcess = true;
conditionA.signalAll();
} finally {
lock.unlock();
}
}
}
}
Author: Jiayi Yang
Link: https://jiayiy.github.io/2020/04/16/Lc-1115/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.