Package Org.rui.thread.block;import Java.util.concurrent.executorservice;import java.util.concurrent.Executors; Import java.util.concurrent.timeunit;/** * Producer and Consumer * Restaurant * * @author Lenovo * */public class Restaurant {//restaurant r=n EW Restaurant (); Meal Meal; Executorservice exec = Executors.newcachedthreadpool (); Waitperson WAITP = new Waitperson (this); Chef chef = new Chef (this);p ublic Restaurant () {Exec.execute (chef); Exec.execute (WAITP);} public static void Main (string[] args) {new Restaurant ();}} Meal class Meal {private final int ordernum;public Meal (int ordernum) {this.ordernum = Ordernum;} Public String toString () {return ' Meal ' + Ordernum;}} Waiter class Waitperson implements Runnable {private Restaurant restaurant;public Waitperson (Restaurant r) {Restaurant = R; }public void Run () {try {while (! Thread.interrupted ()) {synchronized (this) {while (restaurant.meal = = null)//If the meal is empty, the waiter waits for Wait ();} System.out.println ("Waitperson got" + restaurant.meal);//Cook the meal in sync and inform the chef synchronized (RestauranT.chef) {restaurant.meal = Null;restaurant.chef.notifyall ();//Prepare Another}}} catch (Interruptedexception e) { System.out.println ("Waitperson Interrupted");}} Chef Class Chef implements Runnable {Restaurant restaurant;private int count = 0;public Chef (Restaurant r) {Restaurant = R; } @Overridepublic void Run () {try {while (! Thread.interrupted ()) {/** * The chef sends the meal and notifies the waiter to wait until the waiter collects the order and notifies the chef */synchronized (this) {while (restaurant.meal! = null)// The program that waits while preventing missed signals (if there may be other threads taking the order) wait (); if (++count = = ten) {System.out.println ("Out of the food, closing"); Restaurant.exec.shutdownNow (); System.out.print ("Order up!"); /In the Waiter lock sync synchronized (RESTAURANT.WAITP) {restaurant.meal = new meal (count);//Send meal restaurant.waitP.notifyAll ();// Notify Waiter}timeunit.milliseconds.sleep (100);}} catch (Interruptedexception e) {System.out.println ("Chef Interrupted");}} /**output:order Up!waitperson got Meal 1order Up!waitperson got Meal 2order Up!waitperson got Meal 3order Up!waitperson go T Meal 4order Up!waitperson got Meal 5Order Up!waitperson got Meal 6order Up!waitperson got Meal 7order Up!waitperson got Meal 8order Up!waitperson got Meal 9ou T of food, Closingwaitperson Interruptedorder up! Chef interrupted*/
Java thread producers and consumers