Build a Molecule
This problem simulates the creation of water molecule by grouping three threads representing Hydrogen and Oxygen atoms.
We'll cover the following...
Problem
Suppose we have a machine that creates molecules by combining atoms. We are creating water molecules by joining one oxygen and two hydrogen atoms. The atoms are represented by threads. The machine will wait for the required atoms (threads), then group one oxygen and two hydrogen threads to simulate the creation of a molecule. The molecule then exists the machine. You have to ensure that one molecule is completed before moving onto the next molecule. If more than the required number of threads arrive, they will have to wait. The figure below explains the working of our machine:
Two Hydrogen threads are admitted in the machine as they arrive but when the third thread arrives in step 3, it is made to wait. When an Oxygen thread arrives in step 4, it is allowed to enter the machine. A water molecule is formed in step 5 which exists the machine in step 6. That is when the waiting Hydrogen thread is notified and the process of creating more molecules continues. The threads can arrive in any order which means that HHO, OHH and HOH are all valid outputs.
The code for the class is as follows: