Skip to content

Commit 1bf1b99

Browse files
authored
Create Building H2O.java
1 parent 21c5b71 commit 1bf1b99

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

Concurrency/Building H2O.java

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
class H2O {
2+
private Semaphore hydrogen;
3+
private Semaphore oxygen;
4+
private Semaphore mutex;
5+
6+
public H2O() {
7+
this.hydrogen = new Semaphore(2);
8+
this.oxygen = new Semaphore(0);
9+
this.mutex = new Semaphore(1);
10+
}
11+
12+
public void hydrogen(Runnable releaseHydrogen) throws InterruptedException {
13+
// releaseHydrogen.run() outputs "H". Do not change or remove this line.
14+
this.hydrogen.acquire();
15+
releaseHydrogen.run();
16+
this.oxygen.release();
17+
}
18+
19+
public void oxygen(Runnable releaseOxygen) throws InterruptedException {
20+
this.mutex.acquire();
21+
this.oxygen.acquire(2);
22+
releaseOxygen.run();
23+
this.hydrogen.release(2);
24+
this.mutex.release();
25+
}
26+
}

0 commit comments

Comments
 (0)