Java implements producer consumer issues

Source: Internet
Author: User

Introduction

Producer and consumer issues are a classic problem in threading models: producers and consumers share the same storage space during the same time period , as shown in, producers store data in space, and consumers access data, If not coordinated, the following conditions may occur:

Producer Consumer Chart

Storage space is full, and producers occupy it, consumers wait for producers to give up space to remove products, producers wait for consumers to consume products, thereby adding products to the space. Wait for each other, thus the deadlock occurs.

Three ways in which Java solves threading models

1. Wait () and notify ()

Import Java.util.linkedlist;public class Producerconsumer {private linkedlist<object> storehouse = new LinkedLis    T<object> ();    private int MAX = 10;        Public Producerconsumer () {} public void Start () {New Producer (). Start ();    New Comsumer (). Start (); } class Producer extends Thread {public void run () {while (true) {synchronized (STO Rehouse) {try {while (storehouse.size () = = MAX) {S                            Ystem.out.println ("Storehouse is full, please wait");                        Storehouse.wait ();                        } Object Newob = new Object ();                            if (Storehouse.add (Newob)) {System.out.println ("Producer put a Object to storehouse");                            Thread.Sleep ((Long) (Math.random () * 3000));                        Storehouse.notify ();    }                } catch (Interruptedexception IE) {System.out.println ("producer is interrupted!")                    ; }}}}} class Comsumer extends Thread {public void run () {WHI Le (True) {synchronized (storehouse) {try {while (STOREHOUSE.S                            ize () = = 0) {System.out.println ("Storehouse is empty, please wait");                        Storehouse.wait ();                        } storehouse.removelast ();                        System.out.println ("Comsumer get a Object from storehouse");                        Thread.Sleep ((Long) (Math.random () * 3000));                    Storehouse.notify ();                    } catch (Interruptedexception IE) {System.out.println ("Consumer is interrupted"); }}}} publicstatic void Main (string[] args) throws Exception {Producerconsumer pc = new Producerconsumer ();    Pc.start (); }}

2, await () and signal (), the way the thread locks

Package Sort;import Java.util.linkedlist;import Java.util.concurrent.locks.condition;import    Java.util.concurrent.locks.lock;import Java.util.concurrent.locks.reentrantlock;public class ProducerConsumer {    Private linkedlist<object> myList = new linkedlist<object> ();    private int MAX = 10;    Private Final lock lock = new Reentrantlock ();    Private final Condition full = lock.newcondition ();    Private final Condition empty = Lock.newcondition ();        Public Producerconsumer () {} public void Start () {New Producer (). Start ();    New Consumer (). Start ();        public static void Main (string[] args) throws Exception {Producerconsumer s2 = new Producerconsumer ();    S2.start ();                } class Producer extends Thread {public void run () {while (true) {Lock.lock (); try {while (mylist.size () = = MAX) {System.out.println ("Warning:it               ' s full! ");         Full.await ();                    } Object o = new Object ();                        if (Mylist.add (o)) {System.out.println ("Producer:" + O);                    Empty.signal ();                }} catch (Interruptedexception IE) {System.out.println ("producer is interrupted!");                } finally {Lock.unlock ();                }}}} class Consumer extends Thread {public void run () {while (true) {                Lock.lock ();                        try {while (mylist.size () = = 0) {System.out.println ("Warning:it ' s empty!");                    Empty.await ();                    } Object o = Mylist.removelast ();                    System.out.println ("Consumer:" + O);                Full.signal (); } catch (Interruptedexception IE) {systeM.OUT.PRINTLN ("Consumer is interrupted!");                } finally {Lock.unlock (); }            }        }    }}

3, blocking the way of the queue

Import java.util.concurrent.*;p Ublic class Producerconsumer {//Create a blocking queue private linkedblockingqueue<object>    Queue = new linkedblockingqueue<object> (10);        Public Producerconsumer () {} public void Start () {New Producer (). Start ();    New Consumer (). Start ();        public static void Main (string[] args) throws Exception {Producerconsumer s3 = new Producerconsumer ();    S3.start ();                    } class Producer extends Thread {public void run () {while (true) {try {                    Object o = new Object ();                    Take out an object Queue.put (o);                System.out.println ("Producer:" + O);                } catch (Interruptedexception e) {System.out.println ("producer is interrupted!");            }//}}}} class Consumer extends Thread {public void run () { while (true) {try {                    Take out an object o = Queue.take ();                System.out.println ("Consumer:" + O);                } catch (Interruptedexception e) {System.out.println ("producer is interrupted!"); }                // }            }        }    }}

Conclusion

Three ways the principle of the same, are exclusive space lock, blocking and wake-up threads, the first way to compare the traditional, the third way is the simplest, just storage and access, thread synchronization operations by Linkedblockingqueue.

Java implements producer consumer 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.