import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.Condition; public class SodaMachine { private final Lock lock = new ReentrantLock(); private final Condition hasSodaToBuy = lock.newCondition(); private final Condition needsRefill = lock.newCondition(); private final int capacity; private int sodaCount = 0; public SodaMachine(int capacity) { this.capacity = capacity; } public void buySoda() { lock.lock(); try { while (sodaCount == 0) { hasSodaToBuy.await(); } sodaCount--; System.out.println("Buying a soda, remaining count is " + sodaCount); if (sodaCount == 0) { needsRefill.signalAll(); } } catch (InterruptedException e) { System.out.println("Got interrupted while trying to buy soda."); } finally { lock.unlock(); } } public void refill() { lock.lock(); try { while (sodaCount > 0) { needsRefill.await(); } sodaCount = capacity; System.out.println("Refilling, soda count is " + sodaCount); hasSodaToBuy.signalAll(); } catch (InterruptedException e) { System.out.println("Got interrupted while trying to refill."); } finally { lock.unlock(); } } }