Implement an H() method and an O() method to produce a water molecular

Implement an H() method and an O() method to produce a water molecular

Both methods are to be called by multiple threads. Each thread calling either method becomes blocking and when one thread finds that there are already at least two threads calling H() and at least one thread calling O(), let two threads calling H() and one thread calling O() resume from blocking in order to produce a water molecular.

A solution using java.util.concurrent.locks.ReentrantLock.

  1. import java.util.concurrent.locks.Condition;
  2. import java.util.concurrent.locks.Lock;
  3. import java.util.concurrent.locks.ReentrantLock;
  4.  
  5. public class H2O {
  6.  
  7.   static final int H = 0;
  8.   static final int O = 1;
  9.   static final Lock LOCK = new ReentrantLock();
  10.   static final Condition ENOUGH[] = {LOCK.newCondition(), LOCK.newCondition()};
  11.   static final int NEEDED[] = {2, 1};
  12.   static final int COUNT[] = {0, 0};
  13.  
  14.   static void run(int index) {
  15.     LOCK.lock();
  16.     try {
  17.       if(COUNT[H] >= NEEDED[H] && COUNT[O] >= NEEDED[O]) {
  18.         for(int i = 0, n = NEEDED[H]; i < n; ++i) {
  19.           ENOUGH[H].signal();
  20.         }
  21.         COUNT[H] -= NEEDED[H];
  22.         for(int i = 0, n = NEEDED[O]; i < n; ++i) {
  23.           ENOUGH[O].signal();
  24.         }
  25.         COUNT[O] -= NEEDED[O];
  26.       }
  27.       ++COUNT[index];
  28.       ENOUGH[index].awaitUninterruptibly();
  29.     } finally {
  30.       LOCK.unlock();
  31.     }
  32.   }
  33.  
  34.   public static void h() {
  35.     run(H);
  36.   }
  37.  
  38.   public static void o() {
  39.     run(O);
  40.   }
  41. }

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.

More information about formatting options

To prevent automated spam submissions leave this field empty.