原题链接在这里: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 }
标签:third,thread,Order,second,Semaphore,Print,LeetCode,public,first From: https://www.cnblogs.com/Dylan-Java-NYC/p/16791308.html