"Thinkinginjava" 62, producers and consumers

Source: Internet
Author: User

/*** Book: Thinking in Java * Features: producer and Consumer: * Please consider such a person hotel, it has a chef and a waiter. The waiter must wait for the cook to prepare the meal. When the chef is ready, he notifies the waiter, then the waiter will serve, then return to wait. * File: restaurant.java* time: May 8, 2015 18:23:01* Author: cutter_point*/package Lesson21concurency;import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;import Java.util.concurrent.TimeUnit; Import static Net.mindview.util.print.*;class meal//meal class {Private final int ordernum;//order number public Meal (int ordernum) { This.ordernum = Ordernum; }//initialization, the number of meals public String toString () {return "Meal" + This.ordernum;}} Guest Human class Waitperson implements Runnable{private Restaurant restaurant;//a restaurant class public Waitperson (Restaurant R) { Restaurant = R; }//constructor, where is the restaurant you are going to? @Overridepublic void Run () {//For a guest, it is waiting for his food try{while (! Thread.interrupted ())///As long as the thread is not interrupted {synchronized (this)//when the guest is taken this thread {while (restaurant.meal = = null)// No food. this.wait (); Wait for the chef to do the food}print ("Guests get" + restaurant.meal);//Guests get food, ready to eat synchronized (restaurant.chef) {restaurant.meal = null;// The food is finished restaurant.chef.noTifyall (); The food is sold out, the chef wakes up to make food}}} catch (Interruptedexception e) {print ("The guest has no food to eat, gone!") ");}}} Class Chef implements Runnable{private Restaurant restaurant;//chef's Restaurant private int count = 0;public Chef (Restaurant Restau rant) {this.restaurant = restaurant;} @Overridepublic void Run () {//First thread cannot be interrupted try{while (! Thread.interrupted ()) {///when the thread is not interrupted synchronized (this)//locks the block and cannot execute {while (restaurant.meal! = null) When no lock is obtained for the current object This.wait ();//thread into wait, as long as there is food, then you have to wait for}//when called 10 times, then said the food finished, close if (++count = =) {print ("food sold out, closed");//stop thread// Restaurant.exec.shutdown (); Restaurant.exec.shutdownNow ();//This function is to send interrupt interrupt request to all tasks initiated by Executorservice} PRINTNB ("Serve the dishes!" ");//When not called 10 times, there is food synchronized (Restaurant.waitperson)//When the thread gets the guest object in this restaurant {restaurant.meal = new meal (count)  ;//production of count sets of food restaurant.waitPerson.notifyAll (); Wake up the guests, can start eating}timeunit.milliseconds.sleep (100); Break 100 Msec}} catch (Interruptedexception e) {print ("The chef was fired!") ");}}} Restaurant class public class restaurant{//restaurant food, guest, waiter meal meal;//thread connection pool Executorservice exec = ExecutorS.newcachedthreadpool (); Waitperson Waitperson = new Waitperson (this); Chef chef = new Chef (this);//good, food has, the guests have, the chef also has, this restaurant does not rub much can work//create a restaurant, put into operation public Restaurant () {//With thread connection pool,  Work together with these three threads Exec.execute (chef);  Chef put into work exec.execute (Waitperson); The guest}public static void Main (string[] args) {new Restaurant ();//Put in a restaurant}}


Serve the dishes! -obj2 Guest got Meal 1 obj1
Serve the dishes! -obj2 Guest got Meal 2 obj1
Serve the dishes! -obj2 Guest got Meal 3 obj1
Serve the dishes! -obj2 Guest got Meal 4 obj1
Serve the dishes! -obj2 Guest got Meal 5 obj1
Serve the dishes! -obj2 Guest got Meal 6 obj1
Serve the dishes! -obj2 Guest got Meal 7 obj1
Serve the dishes! -obj2 Guest got Meal 8 obj1
Serve the dishes! -obj2 Guest got Meal 9 obj1
The food is sold out and the obj1 shut.
Serve the dishes!  -obj2 the guest had no food to eat, went away! Obj1
The chef is fired! Obj1

"Thinkinginjava" 62, producers and consumers

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.