原题链接在这里:https://leetcode.com/problems/print-in-order/

题目:

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().

Note:

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

Example 1:

Input: nums = [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: nums = [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.

Constraints:

  • nums is a permutation of [1, 2, 3].

题解:

Have semaphore to make sure order is called based on order.

Time Complexity: O(1).

Space: O(1).

AC Java:

 1 class Foo {
 2     Semaphore run1;
 3     Semaphore run2;
 4     Semaphore run3;
 5     public Foo() {
 6         run1 = new Semaphore(1);
 7         run2 = new Semaphore(0);
 8         run3 = new Semaphore(0);
 9     }
10 
11     public void first(Runnable printFirst) throws InterruptedException {
12         run1.acquire();
13         // printFirst.run() outputs "first". Do not change or remove this line.
14         printFirst.run();
15         run2.release();
16     }
17 
18     public void second(Runnable printSecond) throws InterruptedException {
19         run2.acquire();
20         // printSecond.run() outputs "second". Do not change or remove this line.
21         printSecond.run();
22         run3.release();
23     }
24 
25     public void third(Runnable printThird) throws InterruptedException {
26         run3.acquire();
27         // printThird.run() outputs "third". Do not change or remove this line.
28         printThird.run();
29         run1.release();
30     }
31 }

 

原文地址:http://www.cnblogs.com/Dylan-Java-NYC/p/16791308.html

1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长! 2. 分享目的仅供大家学习和交流,请务用于商业用途! 3. 如果你也有好源码或者教程,可以到用户中心发布,分享有积分奖励和额外收入! 4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解! 5. 如有链接无法下载、失效或广告,请联系管理员处理! 6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需! 7. 如遇到加密压缩包,默认解压密码为"gltf",如遇到无法解压的请联系管理员! 8. 因为资源和程序源码均为可复制品,所以不支持任何理由的退款兑现,请斟酌后支付下载 声明:如果标题没有注明"已测试"或者"测试可用"等字样的资源源码均未经过站长测试.特别注意没有标注的源码不保证任何可用性