跳转至

1114. Print in Order

Leetcode

Suppose we have a class:

public class Foo {
  public void first() { print("first"); }
  public void second() { print("second"); }
  public void third() { print("third"); }
}

The same instance of Foo will be passed to three different threads. Thread A will call first(), thread B will call second(), and thread C will call third(). Design a mechanism and modify the program to ensure that second() is executed after first(), and third() is executed after second().

Example 1:

Input: [1,2,3]
Output: "firstsecondthird"
Explanation: There are three threads being fired asynchronously. 
    The input [1,2,3] means thread A calls first(), thread B calls second(), 
    and thread C calls third(). "firstsecondthird" is the correct output.

Example 2:

Input: [1,3,2]
Output: "firstsecondthird"
Explanation: The input [1,3,2] means thread A calls first(), thread B calls third(),
    and thread C calls second(). "firstsecondthird" is the correct output.

Note:

We do not know how the threads will be scheduled in the operating system, even though the numbers in the input seems to imply the ordering. The input format you see is mainly to ensure our tests' comprehensiveness.

分析

最简单的方法是直接使用变量来判断线程是否执行完毕,并使用volatile关键字保证可见性。

class Foo {
    private volatile boolean firstOk = false;
    private volatile boolean secondOk = false;
    public Foo() {
    }

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

    public void second(Runnable printSecond) throws InterruptedException {
        while (!firstOk) ;
        // printSecond.run() outputs "second". Do not change or remove this line.
        printSecond.run();
        secondOk = true;
    }

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

或者使用信号量来同步

class Foo {
    Semaphore f1, f2;
    public Foo() {
        f1 = new Semaphore(0);
        f2 = new Semaphore(0);
    }

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

    public void second(Runnable printSecond) throws InterruptedException {
        // printSecond.run() outputs "second". Do not change or remove this line.
        f1.acquire();
        printSecond.run();
        f2.release();
    }

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