-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy path1117.Building-H2O.java
More file actions
38 lines (29 loc) · 920 Bytes
/
1117.Building-H2O.java
File metadata and controls
38 lines (29 loc) · 920 Bytes
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
// https://leetcode.com/problems/building-h2o/
//
// algorithms
// Hard (38.48%)
// Total Accepted: 197
// Total Submissions: 512
// beats 100.0% of java submissions
import java.util.concurrent.Semaphore;
class H2O {
private Semaphore hSemaphore = new Semaphore(0);
private Semaphore oSemaphore = new Semaphore(1);
private int count;
public H2O() {}
public void hydrogen(Runnable releaseHydrogen) throws InterruptedException {
hSemaphore.acquire();
// releaseHydrogen.run() outputs "H". Do not change or remove this line.
releaseHydrogen.run();
count++;
if ((count & 1) == 0) {
oSemaphore.release();
}
}
public void oxygen(Runnable releaseOxygen) throws InterruptedException {
oSemaphore.acquire();
releaseOxygen.run();
hSemaphore.release();
hSemaphore.release();
}
}