-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConcurrencyPrintInOrder.java
45 lines (40 loc) · 1.29 KB
/
ConcurrencyPrintInOrder.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import java.util.concurrent.Semaphore;
/**
* LeetCode
* 1114. Print in Order
* https://leetcode.com/problems/print-in-order/
* #Easy
*/
@SuppressWarnings("unused")
public class ConcurrencyPrintInOrder {
private final Semaphore[] semaphore = {
new Semaphore(1),
new Semaphore(1),
new Semaphore(1)};
public ConcurrencyPrintInOrder() {
try {
for (int i = 1; i < semaphore.length; i++) {
semaphore[i].acquire();
}
} catch (Exception ignored) {
}
}
public void first(Runnable printFirst) throws InterruptedException {
semaphore[0].acquire();
// printFirst.run() outputs "first". Do not change or remove this line.
printFirst.run();
semaphore[1].release();
}
public void second(Runnable printSecond) throws InterruptedException {
semaphore[1].acquire();
// printSecond.run() outputs "second". Do not change or remove this line.
printSecond.run();
semaphore[2].release();
}
public void third(Runnable printThird) throws InterruptedException {
semaphore[2].acquire();
// printThird.run() outputs "third". Do not change or remove this line.
printThird.run();
//semaphore[0].release();
}
}