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