The waiting-wake mechanism of producer and consumer in Java Multi-threading @version1.0

Source: Internet
Author: User
Tags thread class

One, the producer consumer model student class member variable production and consumption demo, first edition
1. Wait for wake-up:
There are three methods available in the object class:
Wait (): Wait
Notify (): Wake up a single thread
Notifyall (): Wake All Threads
2. Why are these methods not defined in the thread class?
Calls to these methods must be called through the lock object, and the lock object we just used is an arbitrary lock object.
Therefore, these methods must be defined in the object class.
3, when we use multi-threading sometimes need, a thread to produce one data, another thread to consume a data, while the production side of consumption, there is no redundant data generation, and no empty data is consumed.

4. Problem solving Solution The first step is to ensure thread synchronization security: (1) lock,

A: Different kinds of threads have to be locked.
B: The locks of different kinds of wire loads must be the same.

5. Problem solution The second step is to ensure that the data is consumed in a single production: (Waiting for a wake-up mechanism).

6, in the following new two threads, the two threads to manipulate the object are learning class, a thread to produce student object data, a thread consumption of student object data, and do, there is data to consume, no data on the wait, no data on the production, there is data waiting.

//==========================

The first case is the student class object, which is very simple to define two member variables, and a tag to wake the thread.

1  Public class Student {2      Public String name; 3      Public int Age ; 4     boolean flag;  // The default is False---> No data, if TRUE indicates there is data.  5     6 }

The following is a demo of the producer student object

The student object is passed in the construction method to ensure that the producer and the consumer are working with the same object.

1  Public classSetthreadImplementsRunnable {2     PrivateStudent S;3     intx = 0;4 5      PublicSetthread (Student s) {6          This. S =s;7     }8 9 @OverrideTen      Public voidrun () { One          while(true) { A             synchronized(s) { -                 //wake-up mechanism, the producer, first judge there is no oh, there is waiting to be consumed, there is no production data ready to be consumed.  -                 if(s.flag) { the                     Try { - s.wait (); -}Catch(interruptedexception e) { -                         //TODO auto-generated Catch block + e.printstacktrace (); -                     } +                 } A                  at                 //once the flag is marked False, execute the following code -                  -                 if(x% 2 = = 0) { -S.name = "Java"; -S.age = 25; -}Else { inS.name = "Android"; -S.age = 20; to                 } +X + +; -                 //data production once, at this time have the data need to change the mark, the next cycle begins, it is not in production, theS.flag =true; *  $                 //wake-Up threadPanax Notoginseng s.notify (); -             } the  +         } A     } the  +}

The following is the student object of the consumer model demo

The student object is passed in the construction method to ensure that the producer and the consumer are working with the same object.

1  Public classGetThreadImplementsRunnable {2     PrivateStudent S;3 4      PublicGetThread (Student s) {5          This. S =s;6     }7 8      Public voidrun () {9          while(true) {Ten             //wake-up mechanism consumer, there is data on consumption, no data (!) Just wait for the data to be produced.  One             //Spit No Wait, there is consumption A             synchronized(s) { -                 if(!s.flag) {//Flag--->false executes if the following code: means no data is waiting -                     Try { theS.wait ();//release the lock as soon as you wait, allowing other threads to use the lock. And when it wakes up, it wakes up here, -}Catch(interruptedexception e) { -                         //TODO auto-generated Catch block - e.printstacktrace (); +                     } -                 } +  A                 //Flag--->true: consumer data atSystem.out.println (S.name + "" +s.age); -                 //after the consumption, the data is not, modify the Mark -S.flag =false; -                 //wake-Up thread -                 //wake does not mean that you can immediately get execution right, at this time still need to rob CPU execution, - s.notify ();  in             } -         } to     } +}

The following is a test case, which simply creates two threads and then launches the producer and consumer

1 /*2 * How to share one data in multiple classes under the same package:3 * This data is created in the outside world and then passed to other classes through the construction method. 4  */5  Public classDemo {6      Public Static voidMain (string[] args) {7         //shared data, created externally, as parameters, by constructing common8Student s =NewStudent ();9         //using the same parameter in a constructTenSetthread st =NewSetthread (s); OneGetThread GT =NewGetThread (s); A  -Thread T1 =NewThread (ST);//Setting up data -Thread t2 =NewThread (GT);//Get Data the  - T2.start (); - T1.start (); -  +     } -}

  

The waiting-wake mechanism of producer and consumer in Java Multi-threading @version1.0

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.