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 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.
Constraints:
- If an oxygen thread arrives at the barrier when no hydrogen threads are present, it must wait for two hydrogen threads
- If a hydrogen thread arrives at the barrier when no other threads are present, it must wait for an oxygen thread and another hydrogen thread
- Threads pass the barriers in complete sets of three (1 oxygen + 2 hydrogen)
Write synchronization code for oxygen and hydrogen molecules that enforces these constraints.
Input & Output
Constraints
- 1 ≤ n ≤ 1000
- n represents total number of threads
- Threads arrive in any order
- Must form complete H2O molecules