Java implementation of producer consumer problems

Source: Internet
Author: User
Tags stub

Producers and consumers are multi-threaded classic problem, the core of producer and consumer problem is the synchronization problem, the core of synchronization problem is to ensure the integrity of the same resource by multiple threads concurrent access, the common method is to use a signal or lock mechanism, to ensure that resources can only be accessed by one thread at any one time. There are 4 main ways that this problem can be implemented in Java. 1.wait ()/notify (); 2.await ()/signal (); 3.blockingQuene 4.pipedinputstream/pipedoutputstream

The following are implemented separately.

1. Use Wait () and notify () to implement

Wait () method: When the buffer is empty/full, the producer/consumer stops its own execution, discards the lock, and puts itself in a wait state for other threads to execute.

Notify () Method: When a producer/consumer puts a product into a buffer, it sends an executable notification to the other waiting thread while discarding the lock, leaving itself in a wait state.

Here's a look at the code implementation:

First define the store class:

Package Consumerandproducerproblem; Import java.util.LinkedList;    /** * @author: Zhuwei * @ClassName: Store class * @Description: TODO * @Date: PM 3:58:01 */public class storage{//define warehouse maximum capacity 100    Private final int max_size = 100;       Private linkedlist<object> list= new linkedlist<> ();           Production num commodity public void produce (int num) throws Exception {synchronized (list) {//If the warehouse capacity is insufficient                           if (List.size () +num>max_size) {System.out.println ("Insufficient storage capacity");           Thread waits for list.wait ();           }//Warehouse capacity can be produced by capacity producers, then production for (int i = 0;i < num;i++) {List.add (New Object ());           } System.out.println ("Number of producers producing products:" + num);       List.notifyall (); }}//consumption num commodity public void consume (int num) throws Exception {synchronized (list) {/      /Add the goods in the warehouse can not meet the needs of consumers, the thread waits if (list.size () < num) {        System.out.println ("Goods in the warehouse cannot meet consumer demand");           List.wait ();           } for (int i = 0;i < num;i++) {list.remove ();           } System.out.println ("Consumer goods Quantity:" +num);       List.notifyall ();  }    }}


Defining producer Classes

Package Consumerandproducerproblem;  /** * @author: Zhuwei * @ClassName: Producer thread * @Description: TODO * @Date: PM 3:57:15 */public class Consumer implements Runna ble{     //consumer goods quantity    private int number;       Private Storage Storage;          public void consume (int num)    {       try       {           storage.consume (num);       } catch (Exception e)       {           // TODO Auto-generatedcatch block           e.printstacktrace ();       }    }       public int GetNumber ()    {       return number;    }       public void Setnumber (int number)    {       this.number = number;    }       Public Storage GetStorage ()    {       return Storage;    }       public void Setstorage (Storage Storage)    {       this.storage = Storage;    }       @Override public    Void Run ()    {       //TODO Auto-generatedmethod stub       consume (number);    


Define Consumer classes:

Package Consumerandproducerproblem; /** * @author: Zhuwei * @ClassName: Consumer thread * @Description: TODO * @Date: PM 3:57:38 */public class Producer implements Runna ble{    //The quantity of goods produced by    private int number;       Private Storage Storage;       public void produce (int num)    {       try       {           storage.produce (num);       } catch (Exception e)       {           // TODO Auto-generatedcatch block           e.printstacktrace ();       }    }       public int GetNumber ()    {       return number;    }     public void Setnumber (int number)    {       this.number = number;    }     Public Storage GetStorage ()    {       return Storage;    }     public void Setstorage (Storage Storage)    {       this.storage = Storage;    }     @Override public    Void Run ()    {       //TODO Auto-generatedmethod stub       Produce (number);    


To create a test class:

Package Consumerandproducerproblem; public class test{public     static void Main (string[] args)    {       //TODO Auto-generatedmethod stub       //Warehouse Object       Storage Storage = new Storage ();             Consumer object       Consumer c1 = new Consumer ();       C1.setnumber (ten);       C1.setstorage (storage);       Consumer C2 = new Consumer ();       C2.setnumber (+);       C2.setstorage (storage);             Producer Object       Producer p1 = new Producer ();       P1.setnumber (a);       P1.setstorage (storage);       Producer P2 = new Producer ();       P2.setnumber (+);       P2.setstorage (storage);             P1.run ();       C1.run ();       P2.run ();       C2.run ();          } }


2.await () and signal () methods

Some of the classes used in this method are explained:

Reentrantlock (): A reentrant mutex lock that has the same basic behavior and semantics as the implicit monitor lock accessed using the Synchronized method and the statement, but is more powerful. The Reentrantlock will be owned by a thread that has recently successfully acquired the lock and has not released the lock. When the lock is not owned by another thread, the thread that called lock succeeds in acquiring the lock and returning it. If the current thread already owns the lock, this method will return immediately. You can use the isheldbycurrentthread () and Getholdcount () methods to check whether this condition occurs.

Condition (): Decomposes the Object Monitor method (wait,notify , and notifyall) into distinct objects to The implementation is combined to provide multiple wait set (Wait-set) for each object. Where lock replaces the use of the Synchronized method and the statement, condition replaces the use of the Object monitor method.

A condition (also known as a conditional queue or condition variable ) provides a means for a thread to suspend the thread (that is, let it "wait") until another thread that a state condition might now be true notifies it. Because access to this shared state information occurs in different threads, it must be protected so that a form of lock is associated with that condition. The primary property for waiting to provide a condition is to atomically release the associated lock and suspend the current thread, as Object.wait did.

The condition instance is essentially bound to a lock. To obtain an Condition instance for a particular Lock instance, use its newcondition () method.

The code that defines the warehouse is:

Package ConsumerAndProducerProblem2; Import Java.util.linkedlist;importjava.util.concurrent.locks.condition;import Java.util.concurrent.locks.Lock; Importjava.util.concurrent.locks.ReentrantLock;                 public class storage{//define warehouse capacity privatefinal int max_size = 100;                 privatelinkedlist<object> list = new linkedlist<> ();                 Define lock Privatelock lock = new Reentrantlock ();                 Privatecondition full = lock.newcondition ();                   Privatecondition empty = Lock.newcondition ();         Publicint getmax_size () {returnmax_size;                   }//Production commodity publicvoid produce (int number) throws Exception {//Get lock                   Lock.lock ();                            {//Added warehouse capacity cannot accommodate producer-produced goods, thread blocking while (List.size () +number> max_size)                                 {    SYSTEM.OUT.PRINTLN ("Goods that cannot be produced in warehouse space");                            Full.await ();                            } for (inti = 0;i < number;i++) List.add (NewObject ());                            System.out.println ("Producer Goods Quantity:" +number);                            Full.notifyall ();                                                       Empty.notifyall ();                   Release lock Lock.unlock (); }}//Consumer goods publicvoid consume (int number) throws Exception {//Won                   Have to lock Lock.lock (); Products added to the warehouse cannot meet consumer demand while (List.size () < number) {System                            . OUT.PRINTLN ("Goods in the warehouse cannot meet consumer demand");                   Empty.wait ();                          } for (inti = 0;i<number;i++) {  List.remove ();                   } System.out.println ("Number of consumer products:" +number);                   Full.notifyall ();                                     Empty.notifyall ();                           Release lock Lock.unlock (); }}

the code of the producer, consumer, and test class is saved unchanged

Java implementation of producer consumer problems

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.