package com.eshroe.sweetop.concurrency;<br />import java.util.concurrent.ExecutorService;<br />import java.util.concurrent.Executors;<br />import java.util.concurrent.TimeUnit;<br />import java.util.concurrent.locks.Condition;<br />import java.util.concurrent.locks.Lock;<br />import java.util.concurrent.locks.ReentrantLock;<br />class Car2 {<br />private Lock lock = new ReentrantLock();<br />private Condition condition = lock.newCondition();<br />private boolean waxOn = false;<br />public void waxed() {<br />lock.lock();<br />try {<br />waxOn = true;<br />condition.signalAll();<br />} finally {<br />lock.unlock();<br />}<br />}<br />public void buffed() {<br />lock.lock();<br />try {<br />waxOn = false;<br />condition.signalAll();<br />} finally {<br />lock.unlock();<br />}<br />}<br />public void waitForWaxing() throws InterruptedException {<br />lock.lock();<br />try {<br />while (waxOn == false) {<br />condition.await();<br />}<br />} finally {<br />lock.unlock();<br />}<br />}<br />public void waitForBuffing() throws InterruptedException {<br />lock.lock();<br />try {<br />while (waxOn == true) {<br />condition.await();<br />}<br />} finally {<br />lock.unlock();<br />}<br />}<br />}<br />class WaxOn2 implements Runnable {<br />private Car2 car;<br />public WaxOn2(Car2 car) {<br />this.car = car;<br />}<br />public void run() {<br />try {<br />while (!Thread.interrupted()) {<br />System.out.println("Wax On!");<br />TimeUnit.MILLISECONDS.sleep(200);<br />car.waxed();<br />car.waitForBuffing();<br />}<br />} catch (InterruptedException e) {<br />System.out.println("Exiting via interrupt");<br />}<br />System.out.println("Ending Wax On task");<br />}<br />}<br />class WaxOff2 implements Runnable {<br />private Car2 car;<br />public WaxOff2(Car2 car) {<br />this.car = car;<br />}<br />public void run() {<br />try {<br />while (!Thread.interrupted()) {<br />car.waitForWaxing();<br />System.out.println("Wax Off");<br />TimeUnit.MILLISECONDS.sleep(200);<br />car.buffed();<br />}<br />} catch (InterruptedException e) {<br />System.out.println("Exiting via interrupt");<br />}<br />System.out.println("Ending Wax Off task");<br />}<br />}<br />public class WaxOMatic2 {<br />public static void main(String[] args) throws InterruptedException {<br />Car2 car = new Car2();<br />ExecutorService exec = Executors.newCachedThreadPool();<br />exec.execute(new WaxOn2(car));<br />exec.execute(new WaxOff2(car));<br />TimeUnit.SECONDS.sleep(5);<br />exec.shutdownNow();<br />}<br />}<br />