Package Org.rui.thread.block;import Java.util.concurrent.executorservice;import java.util.concurrent.Executors; Import java.util.concurrent.timeunit;//wax wax electric own active way public class Waxomatic {public static void main (string[] args) thr oWS interruptedexception {Car car = new Car (); Executorservice exec = Executors.newcachedthreadpool (); Exec.execute (new Waxoff (car)); Exec.execute (new Waxon (car)); TimeUnit.SECONDS.sleep (5); Exec.shutdownnow ();//Interrupt All Tasks//Shutdownnow attempt to stop all running active tasks, pause processing of waiting tasks, and return to the list of tasks waiting to run}} Class Car {//for polishing, waxing processing state private Boolean Waxon = false;//waxing public synchronized void waxed () {Waxon = true;//readiness to B Uffnotifyall ();} Polished public synchronized void buffed () {Waxon = false;//ready to another coat of Waxnotifyall (); Wait waxing public synchronized void waitforwaxing () throws Interruptedexception {while (Waxon = = false) {wait ();//suspend this task}}/ /wait polished public synchronized void waitforbuffing () throws Interruptedexception {while (Waxon = true) {wait ();//suspend this task}}}c Lass Waxon implements Runnable {private Car car;public Waxon (car c) {car = c;} @Overridepublic void Run () {try {while (! Thread.interrupted ()) {System.out.println ("Wax on!"); TimeUnit.MILLISECONDS.sleep (car.waxed);//waxing car.waitforbuffing ();//Polishing}} catch (Interruptedexception e) { System.out.println ("Exit by Interruption");//E.printstacktrace ();} System.out.println ("Ending Wax on Task");}} Class Waxoff implements Runnable {private Car car;public Waxoff (car c) {car = c;} @Overridepublic void Run () {try {while (! Thread.interrupted ()) {car.waitforwaxing ();//etc Wax System.out.println ("Wax off!"); TimeUnit.MILLISECONDS.sleep (+); car.buffed ();//Polishing}} catch (Interruptedexception e) {System.out.println ("Exit by Break") ;//E.printstacktrace ();} System.out.println ("Ending Wax Off task");}} /*output: (95% match) Wax On!wax off!wax on!wax off!wax on!wax off!wax on!wax off!wax on!wax off!wax on!wax off!wax on!wax Off!wax On!wax Off!wax on! via interrupt exit ending wax on task exits ending wax off task*/
Collaboration between Java threads Wait () and Notifyall ()