# LeetCode 1117. Building H2O --Java解法--多线程保证执行顺序--AtomicInteger

2020/01/14

There are two kinds of threads, oxygen and hydrogen. Your goal is to group these threads to form water molecules. There is a barrier where each thread has to wait until a complete molecule can be formed. Hydrogen and oxygen threads will be given releaseHydrogen and releaseOxygen methods respectively, which will allow them to pass the barrier. These threads should pass the barrier in groups of three, and they must be able to immediately bond with each other to form a water molecule. You must guarantee that all the threads from one molecule bond before any other threads from the next molecule do.

In other words:

Write synchronization code for oxygen and hydrogen molecules that enforces these constraints.

Example 1:

``````Input: "HOH"
Output: "HHO"
Explanation: "HOH" and "OHH" are also valid answers.
``````

Example 2:

``````Input: "OOHHHH"
Output: "HHOHHO"
Explanation: "HOHHHO", "OHHHHO", "HHOHOH", "HOHHOH", "OHHHOH", "HHOOHH", "HOHOHH" and "OHHOHH" are also valid answers.

``````

Constraints:

Total length of input string will be 3n, where 1 ≤ n ≤ 20. Total number of H will be 2n in the input string. Total number of O will be n in the input string.

Java解法如下：

``````class H2O {
private final AtomicInteger h2o = new AtomicInteger();

public H2O() {

}

public void hydrogen(Runnable releaseHydrogen) throws InterruptedException {
synchronized (h2o) {
// if already release two Hydrogen, wait for Oxygen release
while (h2o.get() == 2) {
h2o.wait();
}
// releaseHydrogen.run() outputs "H". Do not change or remove this line.
releaseHydrogen.run();
h2o.notifyAll();
}
}

public void oxygen(Runnable releaseOxygen) throws InterruptedException {
synchronized (h2o) {
// if already release Oxygen, wait for Hydrogen release
while (h2o.get() < 0) {
h2o.wait();
}