Java implementation of the producer consumer Model (Implementation one)

Source: Internet
Author: User

In multi-threaded and concurrent tool classes, one common idea is the producer-consumer model, where producers are responsible for producing goods, placing items on conveyor belts, and consumers are responsible for acquiring conveyor belts and consumer goods. Now consider only the simplest case where only one item is allowed on the conveyor.

1, the belt is empty, then allows the producer to place the item, otherwise do not put (producer thread wait).

2, after the production of goods, notify consumers can take (thread communication, notify or Notifyall).

2, the belt is not empty, then allow the consumer to take items, otherwise not to take (consumer thread wait).

3, consumers take away the goods, inform the producer can continue production (thread communication, notify or Notifyall).

 Packagecom.smikevon.concurrent;ImportJava.util.Random;/*** @description: Producer consumer model, through wait and notify way to achieve * @date: September 12, 2014 morning 11:39:31*/ Public classproducerconsumer_01 { Public Static voidMain (string[] args) {drop drop=NewDrop (); NewThread (NewProducer (drop)). Start (); NewThread (NewConsumer (drop)). Start (); }}/*** @description: Belt, only one item (message) on top * @date: September 12, 2014 PM 12:03:08*/classdrop{PrivateString message; Private BooleanEmpty =true;  Public synchronizedString Take ()throwsinterruptedexception{ while(empty) {wait (); } Empty=true;        Notifyall (); returnmessage; }     Public synchronized voidPut (String message)throwsinterruptedexception{ while(!empty)        {Wait (); }         This. Message =message; Empty=false;    Notifyall (); }}/*** * @description: The producer randomly puts the string * @date: September 12, 2014 morning 11:53:27*/classProducerImplementsRunnable {Privatedrop drop;  PublicProducer (Drop drop) { This. Drop =drop; }     Public voidrun () {string[] messages= {            "I Am",            "A programmer",            "I'm very proud.",            "Also very proud",            "Dedication to love and hillock",            "Diligence and Dedication",            No regrets,            "Dedication to Youth",            "Hope by learning",            Improve,            Own,            "Done",        }; Try {             for(inti=0;i<messages.length;i++) {System.out.format ("%s: Put information-----------%s%n", Thread.CurrentThread (). GetName (), messages[i]);                Drop.put (Messages[i]); Thread.Sleep (NewRandom (System.currenttimemillis ()). Nextint (5000)); }        } Catch(interruptedexception e) {e.printstacktrace (); }    }}/*** @description: Consumer, with a string, take it Out * @date: September 12, 2014 PM 12:02:35*/classConsumerImplementsrunnable{Privatedrop drop; Consumer (Drop drop) { This. Drop =drop; }     Public voidrun () {Try{String message= "";            SYSTEM.OUT.PRINTLN (drop);  while(! (message = Drop.take ()). Equals ("Done") {System.out.format ("%s: Remove information-------------%s%n", Thread.CurrentThread (). GetName (), message); Thread.Sleep (NewRandom (System.currenttimemillis ()). Nextint (5000)); }        } Catch(interruptedexception e) {e.printstacktrace (); }    }}

The code of the thread wait uses the cyclic test condition (the professional name is called the conditional predicate), as follows

 while (! empty) {            wait ();        }

Because after another thread notifyall, after waking this thread, it is impossible to confirm that the test condition must be met at this time. There is no problem with two threads, but there will be problems with more threads, because you cannot confirm that you are being awakened by the producer thread, and that there may be other threads that have changed the state variable before waking (this is the message in the drop), so there will be an exception. It is therefore necessary to test whether the condition has been fulfilled immediately after being awakened. To pass the consistency guarantee to the race condition (Notifyall is to wait for the thread to compete to acquire the lock of the object) is bad to become the habit.

The following section (Implementation II) introduces Reenrantlock, which breaks down the wait and wake conditions, allowing you to give the conditional true meaning, rather than binding the meaning to the lock's hold (wait is telling the thread to hang and notify is to tell the thread to preempt the object's built-in lock).

Java implementation of the producer consumer Model (Implementation one)

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.