Importjava.util.LinkedList;Importjava.util.concurrent.locks.Condition;ImportJava.util.concurrent.locks.Lock;ImportJava.util.concurrent.locks.ReentrantLock;/*** Conditiontest * A test class, with condition implementation of producer consumer issues*/ Public classConditiontest {/*define a container (linked list, queue)*/ PrivateLinkedlist<string>buffer; /*the container can hold the maximum number of elements, initialized by constructors*/ Private intmaxSize; Privatelock lock; PrivateCondition fullcondition; PrivateCondition notfullcondition; Conditiontest (intmaxSize) { This. maxSize =maxSize; Buffer=NewLinkedlist<string>(); Lock=NewReentrantlock (); Fullcondition=lock.newcondition (); Notfullcondition=lock.newcondition (); } /*** put element in container*/ Public voidSet (String string)throwsinterruptedexception {//Get lockLock.lock (); Try { while(MaxSize = =buffer.size ()) { //full, the added thread goes into a wait statenotfullcondition.await (); } buffer.add (String); //when the container is not empty, the waiting read thread is sent a signal to wake the threads to readfullcondition.signal (); } finally{lock.unlock (); } } /*** get element from container*/ PublicString get ()throwsinterruptedexception {string string; Lock.lock (); Try { while(buffer.size () = = 0) { //if the container is empty, the read thread enters the wait statefullcondition.await (); } string=Buffer.poll (); //sends a signal to the written thread to wake up these threads to write to the containernotfullcondition.signal (); } finally{lock.unlock (); } returnstring; }}
Java reentrantlock Condition Conditions (Java Code Combat-002)