Packagecn.study.concurrency.ch14;Importjava.util.concurrent.locks.Condition;ImportJava.util.concurrent.locks.Lock;ImportJava.util.concurrent.locks.ReentrantLock;/*** Use condition as the signal to suspend the thread * This is the FIFO queue *@authorxiaof * *@param<T>*/ Public classConditionboundedbuffer<t> { protected FinalLock lock =NewReentrantlock (); //Data Queue Length Private Static Final intBuffer_size = 1024; //establish two condition, one representative not empty, one representative dissatisfied Private FinalCondition Notfull =lock.newcondition (); Private FinalCondition Notempty =lock.newcondition (); Private Finalt[] items = (t[])NewObject[buffer_size]; Private inttail, head, count; Public voidPut (T x)throwsinterruptedexception {lock.lock ();//this place is locked in operation. Try { while(Count = =items.length) {//if it is full, suspend the thread and wait for the notfull to becomenotfull.await (); } Items[tail]=x; //determine if a full queue has been reached if(++tail = =items.length) Tail= 0; //Count value + +++count; //Insert the data, the queue is definitely not empty, then the non-empty signal is releasednotempty.signal (); } finally{ //after execution, remember to unlockLock.unlock (); } } //get data, block until there is data in the queue PublicT Take ()throwsinterruptedexception {lock.lock ();//before operation, lock first Try { while(count = = 0) { //If there is no data in the queue, then live suspend is necessarynotempty.await (); } //get the data that is used to returnT t =Items[head]; Items[head]=NULL;//the output data is set to NULL. if(++head = =items.length) Head= 0;//Reset the index in the team--count;//Count minus oneNotfull.signal ();//Wake-up insert operation, because get out of a data, then the queue must have empty returnT; } finally { //remember to unlock after execution, whether it's successful or notLock.unlock (); } } }
"Java Concurrency Programming Combat" 12, using condition implementation of multi-threaded bounded cache FIFO queue