Java Simulation for consumer and producer issues

Source: Internet
Author: User

Topic Requirements

Simulation with Java code: A person keeps putting apples in the box, another keeps picking apples from the box, the box can only put 5 apples, the number of apples is unlimited. The classes in the Java.util.concurrent package are not required to be used.

Ideas

This is the main test, the use of Java concurrent Programming, Object.wai (), Object.notify () methods, the use of cyclic queues

1. Use two threads to simulate placing apples and apples separately.

2. Define a class put apples, the class is primarily an array of encapsulation

Attention:

Use of the object.wait () and Object.notify () methods, the following is an excerpt from the JDK1.6 documentation

 public final void Wait () throws Interruptedexception calls this object notify () in other threads method or the Notifyall () method, causing the current thread to wait. In other words, this method behaves as if it were only executing wait (0) calls. The current thread must have this object monitor. The thread releases ownership of this monitor and waits until other threads wake up by calling the Notify method, or the Notifyall method notifies the thread waiting on this object's monitor. The thread then waits to regain ownership of the monitor before it can continue execution. For a version of a parameter, it is possible to implement interrupts and spurious wakes, and this method should always be used in loops: synchronized (obj) {while ( <  condition  does not hold  >  

The personal understanding of the Wait () method is to block the current thread and release the lock until someone calls the Notify () or Notifyall () method to wake. Note that two methods are used for the same object

Notify () is primarily the thread that wakes up the current object blocking. If there are multiple threads, a thread is awakened randomly

The following is the use of circular queues

Determines whether the loop array is empty or full

1. Sacrificing a space

Front = = rear, i.e. empty status (rear + 1)% length = = Front is full

2. Set a flag to record the records that have been placed

int count; Count = = Array.Length is full

I'm using the second method here.

Thread concurrency control can be synchronized using Java sychronized

Here is a concrete implementation

1  Public classTest {2      Public Static voidMain (string[] args) {3Box Box =NewBox ();4Thread producer =NewThread (Newproduceapple (box));5Thread customer =NewThread (Newcustomapple (box));6         7 Producer.start ();8 Customer.start ();9     }Ten } One  A classbox{ -     intBoxlength = 5;//Box Capacity -     intBuff[] =New int[boxlength]; the     intPutpoint = 0; -     intGetPoint = 0; -     intBoxcount = 0;//box has been placed in the quantity - } +  - //production of apples, producers + classProduceappleImplementsrunnable{ A box box; at      -      Publicproduceapple (Box box) { -          This. Box =box; -     } - @Override -      Public voidrun () { in          while(true){ -             synchronized(box) { toBox.putpoint = box.putpoint%box.boxlength; +                 if(Box.boxcount = = 5) {//There is no place to put apples, waiting for consumers to consume apples -                     Try { the box.wait ();  *}Catch(interruptedexception e) { $ e.printstacktrace ();Panax Notoginseng                     } -}//if the                 Else{//produce an apple and put it in the box +box.buff[(++box.putpoint)% box.boxlength] = 1; Abox.boxcount++; theSystem.out.println ("Put in an apple"); +SYSTEM.OUT.PRINTLN ("Total apples:" +box.boxcount); - box.notify (); $                     Try { $Thread.Sleep (1000); -}Catch(interruptedexception e) { - e.printstacktrace (); the                     } -}//ElseWuyi                      the             } -         } Wu          -     }     About } $  - //consumption of apples, consumers - classCustomappleImplementsrunnable{ - box box; A      Publiccustomapple (Box box) { +          This. Box =box; the     } - @Override $      Public voidrun () { the          while(true){ the             synchronized(box) { theBox.getpoint = box.getpoint%box.boxlength; the                 if(Box.boxcount = = 0) {//no apples to eat, waiting for producers to produce apples -                     Try { in box.wait (); the}Catch(interruptedexception e) { the e.printstacktrace (); About                     } the}//if the                 Else{//eat an apple and wake the producer thebox.buff[(++box.getpoint)% box.boxlength] = 0; +System.out.println ("Eat an apple"); -box.boxcount--; theSYSTEM.OUT.PRINTLN ("Total apples:" +box.boxcount);Bayi box.notify (); the                      the                     Try { -Thread.Sleep (1000); -}Catch(interruptedexception e) { the                         //TODO auto-generated Catch block the e.printstacktrace (); the                     } the}//Else -             } the         } the          the     }94      the}

Java simulation for consumer and producer issues

Related Article

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.