Multithreading-producer Consumers

Source: Internet
Author: User

Positive Solutions Blog: 59731447

always call wait and notify in the loop (loop), not in the IF statement

Now you know that wait should always be called in the context of the synchronized and the object that is shared by multithreading, and the next thing to remember is that you should always call wait in the while loop instead of the IF statement. Because threads are waiting under certain conditions-in our case, "If the buffer queue is full, then the producer thread should wait", you might intuitively write an if statement. But there are some subtle minor problems with the IF statement, which can cause your thread to wake up incorrectly even if the condition is not met. So if you do not use the while loop again after the thread is woken up to check if the wake-up condition is met, your program may have errors-for example, when the buffer is full and the producer continues to generate data, or when the buffer is empty, the consumer starts the trumpet data. So remember, always use wait! in the while loop instead of the IF statement I would recommend reading "effective Java", which is the best reference for how to use wait and notify correctly.

Some say this: (HTTP://WWW.TUICOOL.COM/ARTICLES/A6RAM23)

Because in a multi-core processor environment, a Signal wake operation may activate more than one thread (a thread that blocks on a condition variable), allowing multiple calls to wait for the thread to return. So with the while loop to condition multiple judgments, you can avoid this false wake.

Based on the above cognition, here is a canonical code template that uses the wait and notify functions:

12345678 //the standard idiom for Calling the wait method in Java synchronized ( Sharedobject) {      while (condition) {      Code class= "Java Plain" >sharedobject.wait ();          //(releases lock, and reacquires on wakeup)      }      //do action based upon condition e.g. take or put to the queue

As I said before, the purpose of using wait in a while loop is to check whether the condition is satisfied before and after the thread is awakened. If the condition does not change and wait is called before notify's wake-up notification comes up, the thread is not guaranteed to wake up, potentially causing a deadlock problem.

Attention:

1 wait, notify, and Notifyall are always used in synchronized methods or objects, otherwise Java virtual opportunities generate illegalmonitorstateexception.

2 Always use wait in the while loop instead of the IF statement. In this way, the loop checks for wait conditions before and after the thread sleep, and processes the wake-up notification if the condition does not actually change.

3 Use wait on objects that are always shared between multiple threads (in the producer consumer model, the buffer queue).

Producer Consumer Code:

https://zhuanlan.zhihu.com/p/20300609 code has some problems, modify the following

Prosumertoconsumer class
 Public classProsumertoconsumer { Public Static voidMain (string[] args)throwsException { person person=NewPerson (); Thread T1=NewThread (NewProducer (person), "producer T1"); Thread T2=NewThread (NewProducer (person), "producer T2"); Thread T3=NewThread (NewProducer (person), "producer T3"); Thread S1=NewThread (NewConsumer (person), "consumer S1"); Thread S2=NewThread (NewConsumer (person), "Consumer S2"); Thread S3=NewThread (NewConsumer (person), "consumer S3");        S1.start ();        S2.start (); Thread.Sleep (2000);        T1.start ();        T2.start ();                   T3.start (); }}

 Producer Code:

 Public classProducerImplementsRunnable {Privateperson person ;//private String name;          PublicProducer (person person) { This. person=Person ;//This.name=name;} @Override Public voidrun () {Try{person.producer (); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }    }}

consumer code:

 Public class Implements runnable{    private person person ;           Public Consumer (person person) {         the. person= person;    }    @Override    publicvoid  run () {                try  {            Person.consumer ();         Catch (Exception e) {            e.printstacktrace ();     }}}

  Person Code:

 Public classPerson {Private Static volatile intNum=0; PrivateObject obj=NewObject (); Private Static Final intMax_num=5;  Public voidProducer ()throwsinterruptedexception{ while(true){            synchronized(obj) { while(num==max_num) {System.out.println ("box is Full,size =" +num);                Obj.wait (); } num++; System.out.println (Thread.CurrentThread (). GetName ()+num);            Obj.notifyall (); }        }    }         Public voidConsumer ()throwsinterruptedexception{ while(true) {            synchronized(obj) { while(num==0) {System.out.println ("box is Empty,size =" +num);                Obj.wait (); } num--;                Obj.notifyall (); System.out.println (Thread.CurrentThread (). GetName ()+num); }        }        }}

Example Validation 1: If you are using the while data within the queue capacity range.

while (num==max_num)
         while (true            ){synchronized  (obj) {                while (num==max_num) {                    System.out.println ("box is full,size =" + num);                    Obj.wait ();                }

Example Validation 2: If the data is determined to be in the case, it has exceeded the capacity of the queue

if (num==
         while (true            ){synchronized  (obj) {                if(num==max_num) {                    System.out.println ("box is full,size =" + num);                    Obj.wait ();                }

Multithreading-producer 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.