Using Reentrantlock+condition to achieve consumer and producer patterns

Source: Internet
Author: User

import java.util.concurrent.locks.condition;import java.util.concurrent.locks.lock;import  java.util.concurrent.locks.reentrantlock;public class productqueue<t> {     private final t[] items;    private final lock lock  = new reentrantlock ();    private condition notfull =  Lock.newcondition ();     private condition notempty = lock.newcondition ();    //    private int head, tail, count;     public productqueue (int maxsize)  {         items =  (t[])  new Object[maxSize];    }     Public productqueue ()  {        this (Ten);     }  &nbsP; public void put (t t)  throws InterruptedException {         lock.lock ();        try {             while  (Count == getcapacity () )  {                 Notfull.await ();            }             items[tail] = t;             if  (++tail == getcapacity ())  {                 tail = 0;             }             ++couNt;            notempty.signalall ();         } finally {             lock.unlock ();        }     }    public t take ()  throws InterruptedException {         lock.lock ();         try  {            while  (count ==  0)  {                 Notempty.await ();            }             T ret = items[head];             items[head] = null;//gc             //            if  (++head ==  getcapacity ())  {                 head = 0;            }             --count;             notfull.signalall ();             return ret;        } finally {             lock.unlock ();         }    }    public int getcapacity ()  {        return items.length;    }     Public int size ()  {        lock.lock ();         try {             return count;        } finally {             lock.unlock ();         }    }}


Using Reentrantlock+condition to achieve consumer and producer patterns

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.