leetCode4

咱们提供了一个类:异步

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

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

 

示例 1:设计

输入: [1,2,3]
输出: "onetwothree"
解释:
有三个线程会被异步启动。
输入 [1,2,3] 表示线程 A 将会调用 one() 方法,线程 B 将会调用 two() 方法,线程 C 将会调用 three() 方法。
正确的输出是 "onetwothree"。
示例 2:code

输入: [1,3,2]
输出: "onetwothree"
解释:
输入 [1,3,2] 表示线程 A 将会调用 one() 方法,线程 B 将会调用 three() 方法,线程 C 将会调用 two() 方法。
正确的输出是 "onetwothree"。对象

总结:全部的解法都是一个理念,不管采用何种方式,开始时必须执行first线程,而后设置条件知足second执行而first和third线程都不能执行,同时只有first线程执行完才能给与该条件,而后设置条件知足third执行而first和second线程都不能执行,同时只有second线程执行成功后才能给与该条件three

这是一个典型的执行屏障的问题,能够经过构造屏障来实现。rem

以下图,咱们须要构造 22 道屏障,second 线程等待 first 屏障,third 线程等待 second 屏障。:it

first 线程会释放 first 屏障,而 second 线程会释放 second 屏障。io

Java 中,咱们使用线程等待的方式实现执行屏障,使用释放线程等待的方式实现屏障消除。具体代码以下:

代码:
Java
class Foo {

private boolean firstFinished;
private boolean secondFinished;
private Object lock = new Object();

public Foo() {
    
}

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

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

public void third(Runnable printThird) throws InterruptedException {
    
    synchronized (lock) {
       while (!secondFinished) {
            lock.wait();
        }

        // printThird.run() outputs "third". Do not change or remove this line.
        printThird.run();
    } 
}

}咱们使用一个 Ojbect 对象 lock 实现全部执行屏障的锁对象,两个布尔型对象 firstFinished,secondFinished 保存屏障消除的条件。

相关文章
相关标签/搜索