Building producer consumers with Java condition

Source: Internet
Author: User
1.Condition Introduction

In the previous article mentioned the object of the wait and notify method, condition class is actually this method of an alternative product.
The condition object is used in conjunction with lock and is created by lock. And the caller of the condition.await must get lock, which automatically releases the lock at await, and then acquires the lock when it is signal by another thread, a similar use for the sychronized mentioned in the previous blog. 2. Producer consumer procedures based on condition

(seemingly arrayblockingqueue) here use Notfull and notempty to indicate that there is a condition for the elements in the linked list, the specific code is as follows:

package concurrency;
 /** * Created by Wangxiaoyi on 15/11/18.
* * Import java.util.LinkedList;
Import java.util.List;
Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;
Import java.util.concurrent.locks.Condition;
Import Java.util.concurrent.locks.Lock;


Import Java.util.concurrent.locks.ReentrantLock;
    public class ProducerAndConsumer2 {private list<integer> data = new linkedlist<> ();
    private static final int max_data_len = 10;
    Private lock lock = new Reentrantlock ();


    Private Condition Notempty = Lock.newcondition ()//Non-empty condition private Condition notfull = Lock.newcondition ();//Not full condition

        Class Producer implements Runnable {private int pid = 0;
        public Producer (int pid) {this.pid = pid; public void Run () {try {) ' while '!

                    Thread.CurrentThread (). isinterrupted ()) {lock.lock (); while (Data.size () >= MAX_data_len) {System.out.println ("Producer" + pid + "Waiting!")
                        Size: "+ data.size ()); Notfull.await ();
                        Wait for notfull.signal to wake Up} try{Data.add (PID); Notempty.signal (); Wake notempty.await () thread System.out.println ("Producer" + pid + "Add" + pid + "size:" + data.siz

                    E ());
                    }finally {lock.unlock ();
                } thread.sleep (500);
            } catch (Interruptedexception IE) {ie.printstacktrace ();

        }} class Consumer implements runnable{private int cid = 0;
        Public Consumer (int cid) {this.cid = CID; public void Run () {try {) ' while '!

        Thread.CurrentThread (). isinterrupted ()) {lock.lock ();            while (Data.isempty ()) {System.out.println ("Consumer + cid +" waiting, data size:
                        "+ data.size ());
                    Notempty.await ();
                        } try{int pid = data.remove (0);
                        Notfull.signal ();

                    System.out.println ("Consumer" + CID + "consuming data" + PID + "Data size:" + data.size ());
                    }finally {lock.unlock ();
                } thread.sleep (500);
            }}catch (Interruptedexception IE) {ie.printstacktrace ();

        }} public void Start () {Executorservice executor = Executors.newcachedthreadpool ();
            for (int i = 0; i < 5; + + i) {executor.submit (new Producer (i));
        Executor.submit (New Consumer (i));
  try {thread.sleep (10*1000);      catch (Interruptedexception e) {e.printstacktrace ();
    } executor.shutdownnow ();

    public static void Main (String []args) {new ProducerAndConsumer2 (). Start ();
 }


}

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.