Hydrogen thread prints H | Oxygen thread prints O | Ensure output always forms water molecule pattern: HHO

Published on 2026-02-26 18:17 by Frugle Me (Last updated: 2026-02-26 18:17)

#semaphore #h2o #handshake
Share:

Building H2O: A Concurrency Challenge

When working with multi-threaded environments, synchronization is key. In this scenario, we have two types of threads: Hydrogen (printing 'H') and Oxygen (printing 'O'). To form a water molecule, we must ensure they output in a strict HHO pattern.

The Problem

  • Hydrogen threads must wait until there are at least two H threads and one O thread available.
  • Oxygen threads must wait for two H threads to be ready.
  • The output must always be grouped as HHO.

The Solution Strategy

To solve this, we use Semaphores and a Barrier:
1. Hydrogen Semaphore: Initialized to 2.
2. Oxygen Semaphore: Initialized to 1.
3. Cyclic Barrier: Set to 3 to ensure all three threads (H, H, O) finish their print action before the next molecule begins.

Java Implementation Snippet

public class H2O {
private Semaphore hSem = new Semaphore(2);
private Semaphore oSem = new Semaphore(1);
private CyclicBarrier barrier = new CyclicBarrier(3);

public void hydrogen(Runnable releaseHydrogen) throws InterruptedException {
    hSem.acquire();
    try {
        barrier.await();
    } catch (Exception e) {}
    releaseHydrogen.run(); // Prints "H"
    hSem.release();
}

public void oxygen(Runnable releaseOxygen) throws InterruptedException {
    oSem.acquire();
    try {
        barrier.await();
    } catch (Exception e) {}
    releaseOxygen.run(); // Prints "O"
    oSem.release();
}

}

Summary

By controlling the flow with semaphores, we guarantee the 2:1 ratio, and the barrier ensures the threads "handshake" before proceeding to the next H2O molecule.

Comments (0)

Want to join the conversation?

Please log in to add a comment.