Java multithreading-producer and consumer

Source: Internet
Author: User

When talking about multithreading, producers and consumers are always the same level as "Hello World!

Okay. Let's talk about the main ideas:

1. Construct a container class and use the inventory list as the container for storing goods (that is, the warehouse );

2. The Container class provides conventional methods: Constructor (heavy load), get and set methods of the maximum container value, and methods for obtaining the current container commodity volume (see the program for details );

3. Provide the warehouse receiving method: if the container is full, false is returned; otherwise, a "commodity" is imported and a "warehouse picking" thread is notified because the container is empty and is in the waiting state;

4. Provides the warehouse Picking Method: if the container is empty, wait; otherwise, a "commodity" is taken ";

 

Container class (CODE ):

Package COM. fox. producerconsumer; <br/> Import Java. util. inventory list; </P> <p>/** <br/> * @ author huangfox <br/> * use the inventory list to simulate the storage space of the product and provide methods such as loading and picking. <Br/> */<br/> public class queue {<br/> // queue length. The default value is 100. <br/> private int queuemaxlength = 100; <br/> // the inventory list simulates the space for storing items. <Br/> private queue list <Object> queue = new queue list <Object> (); <br/> Public Queue () {</P> <p >}</P> <p> Public Queue (INT maxlength) {<br/> This. queuemaxlength = maxlength; <br/>}</P> <p> Public int getqueuemaxlength () {<br/> return queuemaxlength; <br/>}< br/> Public void setqueuemaxlength (INT queuemaxlength) {<br/> This. queuemaxlength = queuemaxlength; <br/>}</P> <p> Public int getqueuesize () {<br/> return Queue. size (); <br/>}</P> <p>/** <br/> * put an object into the queue (put a commodity into the commodity space) <br/> * @ Param o <br/> * @ return <br/> */<br/> Public synchronized Boolean put (Object O) {<br/> If (getqueuesize ()> = getqueuemaxlength () {<br/> return false; <br/>} else {<br/> queue. add (o); <br/> policyall (); <br/> return true; <br/>}< br/>/** <br/> * retrieves an object from the queue. <Br/> * If the queue is empty, perform corresponding processing: <br/> * 1. if the given waittime is less than 0, wait until it is wait () until it is awakened (wake y (); <br/> * 2. the given waittime is equal to 0 and skipped without waiting. <br/> * 3. if the given waittime is greater than 0, wait for the given time (waittime ); <br/> * @ Param waittime <br/> * @ return <br/> */<br/> Public synchronized object get (INT waittime) {<br/> isempty (waittime); <br/> return queue. poll (); <br/>}</P> <p>/** <br/> * @ Param waittime <br/> */<br/> Public synchronized void isempty (INT waittime) {<br/> If (getqueuesize () <1) {<br/> If (waittime =-1) {<br/> try {<br/> wait (); <br/>} catch (interruptedexception e) {<br/> E. printstacktrace (); <br/>}< br/>} else if (waittime> 0) {<br/> try {<br/> wait (waittime ); <br/>} catch (interruptedexception e) {<br/> E. printstacktrace (); <br/>}< br/>}else {<br/> // <br/>}< br/>}else {</P> <p >}< br />}< br/>}

 

5. Compile a thread-based class that mainly provides "canrun". Why? The main purpose is to keep the thread running. The only way is that the run method does not end. Therefore, you need to use while (canrun) to determine whether the "running status" is used.

 

Thread-based class (CODE)

Package COM. fox. producerconsumer; <br/> public class basethread extends thread {<br/> private Boolean Brun = true; </P> <p> Public Boolean canrun () {<br/> return Brun; <br/>}</P> <p> Public void stoprun () {<br/> Brun = false; <br/>}</P> <p> Public static void sleep (int ms) {<br/> try {<br/> thread. sleep (MS); <br/>}catch (interruptedexception e) {<br/> E. printstacktrace (); <br/>}< br/>

 

6. producer: The producer produces goods under certain conditions (containers are not satisfied) and stores the goods in the database. After an action is completed, yield will notify the "top-up" task to complete, to prevent continuous production, tired of working. Joke!

 

Producer (CODE)

Package COM. fox. producerconsumer; <br/> public class producer extends basethread {<br/> private queue; <br/> private int productno = 0; </P> <p> Public producer (queue q) {<br/> This. queue = Q; <br/>}</P> <p>/** <br/> * determines whether there is space for storing goods. If there is space for storing goods, generate one, store the task in the space and tell the "CPU" that the task is complete. <Br/> */<br/> Public void run () {<br/> while (canrun () {<br/> If (queue. getqueuesize ()> = queue. getqueuemaxlength () {<br/> system. out. println ("no space to store items ...... "); <br/> sleep (500); <br/>}else {<br/> integer p = producing (); <br/> queue. put (p); <br/> thread. yield (); <br/>}</P> <p>/** <br/> * simulate the production of goods. <Br/> * @ return <br/> */<br/> private integer producing () {<br/> integer NO = new INTEGER (productno ++ ); <br/> sleep (100); <br/> system. out. println ("product:" + NO); <br/> return no; <br/>}</P> <p >}< br/>

 

7. Consumer: The Consumer processing process is relatively simple. The same consumption process should end with Yield once.

 

Consumer (CODE)

Package COM. fox. producerconsumer; <br/> public class Consumer extends basethread {<br/> private queue; </P> <p> public consumer (queue q) {<br/> This. queue = Q; <br/>}</P> <p>/** <br/> */<br/> Public void run () {<br/> while (canrun () {<br/> Object o = queue. get (500); <br/> If (o! = NULL) {<br/> consuming (o); <br/> thread. yield (); <br/>}</P> <p>/** <br/> * 500 ms for consuming goods; <br/> * @ Param o <br/> */<br/> Public void consuming (Object O) {<br/> integer NO = (integer) O; <br/> system. out. println ("Consumer Goods:" + NO); <br/> sleep (500); <br/>}< br/>

 

8. mainapp, main program.

 

Package COM. fox. producerconsumer; <br/> Import Java. util. date; <br/> public class mainapp {<br/>/** <br/> * @ Param ARGs <br/> */<br/> Public static void main (string [] ARGs) {<br/> queue q = new Queue (20); <br/> producer P = new producer (Q); <br/> consumer c = new consumer (Q ); <br/> // <br/> system. out. println ("start running, end in 5s! "); <Br/> date bt = new date (); <br/> P. start (); <br/> C. start (); <br/> // <br/> basethread. sleep (5000); <br/> P. stoprun (); <br/> C. stoprun (); <br/> date ET = new date (); <br/> // <br/> try {<br/> P. join (1, 20000); <br/> C. join (20000); <br/>}catch (interruptedexception e) {<br/> E. printstacktrace (); <br/>}< br/> system. out. println ("the main thread ends! "); <Br/> date et2 = new date (); <br/> system. out. println ("from start to end of system execution:" + (ET. gettime ()-BT. gettime (); <br/> system. out. println ("End Time of Production and Consumption threads:" + (et2.gettime ()-et. gettime (); <br/>}< br/>

 

Running result:

Start running. It will end in 5s!
Products produced: 0
Consumer goods: 0
Produced goods: 1
Produced goods: 2
Produced goods: 3
Products produced: 4
Consumer goods: 1
Produced products: 5
Produced products: 6
Products produced: 7
Produced products: 8
Produced goods: 9
Consumer goods: 2
Produced goods: 10
Produced products: 11
Produced goods: 12
Produced goods: 13
Produced products: 14
Produced products: 15
Consumer goods: 3
Produced goods: 16
Produced goods: 17
Produced products: 18
Produced goods: 19
Consumer goods: 4
Produced goods: 20
Produced goods: 21
Produced goods: 22
Produced goods: 23
Produced goods: 24
No space to store items ......
Consumer goods: 5
Produced goods: 25
Consumer goods: 6
Produced goods: 26
No space to store items ......
Consumer goods: 7
Produced goods: 27
No space to store items ......
Consumer goods: 8
Produced goods: 28
No space to store items ......
Consumer goods: 9
Produced goods: 29
No space to store items ......
The main thread ends!
From start to end of system execution: 5000
End Time of Production and Consumption threads: 500

 

Summary:

1. Join: the main thread waits for the termination of the sub-thread, that is, the code after the sub-thread calls the join method. It can only be executed after the sub-thread is completed;

2. Yield: the thread scheduler considers that the current thread has been running for a long time. It is used to let the CPU time slice out to prevent monopoly;

3. Wait, policy: This is a pair of methods;

This method must be called in the synchronized method or block;

The current thread causes wait because of a certain condition. In this thread, the method that can change this condition should execute notify.

 

Note:

Refer to Java build design.

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.