Lc-1114

Lc 1114.按序打印

我们提供了一个类:

public class Foo {
public void one() { print(“one”); }
public void two() { print(“two”); }
public void three() { print(“three”); }
}
三个不同的线程将会共用一个 Foo 实例。

线程 A 将会调用 one() 方法
线程 B 将会调用 two() 方法
线程 C 将会调用 three() 方法
请设计修改程序,以确保 two() 方法在 one() 方法之后被执行,three() 方法在 two() 方法之后被执行。

class Foo {

boolean firstFinished = false;
boolean secondFinished = false;
final Object obj = new Object();

public Foo() {

}

public void first(Runnable printFirst) throws InterruptedException {
synchronized (obj) {
// printFirst.run() outputs "first". Do not change or remove this line.
printFirst.run();
firstFinished = true;
}
}

public void second(Runnable printSecond) throws InterruptedException {
synchronized (obj) {
while (firstFinished) {
// printSecond.run() outputs "second". Do not change or remove this line.
printSecond.run();
secondFinished = true;
}

}
}

public void third(Runnable printThird) throws InterruptedException {
synchronized (obj) {
while (secondFinished) {
// printThird.run() outputs "third". Do not change or remove this line.
printThird.run();
}
}
}
}

提交结果:超时

原因:while循环,不停抢占CPU资源来判断自身是否结束循环(自旋)。

优化

使用wait+notify避免了自旋

class Foo {

final Object obj = new Object();
boolean firstFinished = false;
boolean secondFinished = false;

public Foo() {

}

public void first(Runnable printFirst) throws InterruptedException {
synchronized (obj) {
// printFirst.run() outputs "first". Do not change or remove this line.
printFirst.run();
firstFinished = true;
obj.notifyAll();
}
}

public void second(Runnable printSecond) throws InterruptedException {
synchronized (obj) {
while (!firstFinished) {
obj.wait();
}
// printSecond.run() outputs "second". Do not change or remove this line.
printSecond.run();
secondFinished = true;
obj.notifyAll();
}
}

public void third(Runnable printThird) throws InterruptedException {
synchronized (obj) {
while (!secondFinished) {
obj.wait();
}
// printThird.run() outputs "third". Do not change or remove this line.
printThird.run();
}
}
}

优化:使用CountDownLatch(Semaphore同理)

class Foo {

CountDownLatch c2;
CountDownLatch c3;

public Foo() {
c2 = new CountDownLatch(1);
c3 = new CountDownLatch(1);
}

public void first(Runnable printFirst) throws InterruptedException {
// printFirst.run() outputs "first". Do not change or remove this line.
printFirst.run();
c2.countDown();
}

public void second(Runnable printSecond) throws InterruptedException {
c2.await();
// printSecond.run() outputs "second". Do not change or remove this line.
printSecond.run();
c3.countDown();
}

public void third(Runnable printThird) throws InterruptedException {
c3.await();
// printThird.run() outputs "third". Do not change or remove this line.
printThird.run();
}
}
Author: Jiayi Yang
Link: https://jiayiy.github.io/2020/04/13/Lc-1114/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.