1. Wait () Usage: Wait () is wrapped in a while statement because some other task may suddenly get in and take the order when Waitperson is awakened;
2. Wait (), notify () and Notifyall () can only be called in the synchronous control method or in the synchronization control block;
Importjava.util.concurrent.*; Public classMeal {Private Final intOrdernum; PublicMeal (intordernum) { This. ordernum=Ordernum; } PublicString toString () {return"Meal" +Ordernum; }} Public classRestaurant {Meal Meal; Executorservice exec=Executors.newcachedthreadpool (); Waitperson Waitperson=NewWaitperson ( This); Chef Chef=NewChef ( This); PublicRestaurant () {exec.execute (Waitperson); Exec.execute (chef); }} Public classWaitpersonImplementsrunnable{PrivateRestaurant Restaurant; PublicWaitperson (Restaurant r) {Restaurant=R; } @Override Public voidrun () {Try{ while(!thread.interrupted ()) { synchronized( This) { while(restaurant.meal==NULL) {wait ();//For the chef to produce a meal}} System.out.println ("Waitperson got" +restaurant.meal); synchronized(restaurant.chef) {restaurant.meal=NULL; Restaurant.chef.notifyAll (); } } }Catch(interruptedexception e) {System.out.println ("Waitperson interrupted"); } }} Public classChefImplementsRunnable {PrivateRestaurant Restaurant; Private intCount=0; PublicChef (Restaurant r) {Restaurant=R; } @Override Public voidrun () {Try{ while(!thread.interrupted ()) { synchronized( This){ while(restaurant.meal!=NULL) {wait (); } } if(++count==10) {System.out.println ("Out of Food.closing"); Restaurant.exec.shutdownNow (); } System.out.print ("Order up!"); synchronized(Restaurant.waitperson) {restaurant.meal=NewMeal (count); Restaurant.waitPerson.notifyAll (); } //TimeUnit.MILLISECONDS.sleep (+); } }Catch(interruptedexception e) {System.out.println ("Chef interrupted"); } }}
Java-wait ()/notify ()