Java reentrantlock Condition Conditions (Java Code Combat-002)

Source: Internet
Author: User

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)

Related Article

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.