-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathH2O.java
65 lines (56 loc) · 1.72 KB
/
H2O.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package thread.leetcode1117;
import java.util.concurrent.Semaphore;
/**
* H2O 生成
* LeetCode 1117 https://leetcode-cn.com/problems/building-h2o/
*
* @author yangyi 2022年08月11日17:49:01
*/
public class H2O {
private Semaphore h = new Semaphore(2);
private Semaphore o = new Semaphore(0);
public H2O() {
}
public void hydrogen(Runnable releaseHydrogen) throws InterruptedException {
h.acquire();
// releaseHydrogen.run() outputs "H". Do not change or remove this line.
releaseHydrogen.run();
o.release();
}
public void oxygen(Runnable releaseOxygen) throws InterruptedException {
o.acquire(2);
// releaseOxygen.run() outputs "O". Do not change or remove this line.
releaseOxygen.run();
h.release(2);
}
public static void main(String[] args) {
Runnable h = () -> System.out.println("h");
Runnable o = () -> System.out.println("o");
int n = 3;
H2O h2O = new H2O();
new Thread(new Runnable() {
@Override
public void run() {
try {
for (int i = 0; i < n * 2; i++) {
h2O.hydrogen(h);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
try {
for (int i = 0; i < n; i++) {
h2O.oxygen(o);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
}