Basic usage and attention points of Java condition conditional variables

Source: Internet
Author: User

Recently, looking at Pthread, I recalled the use of conditional variables in Java when I saw the condition variables section.

The conditional variables in Java implement the Java.util.concurrent.locks.Condition interface, and the instantiation of the condition variable is obtained by invoking the Newcondition () method on a lock object, so that The condition is tied to a lock object. Therefore, conditional variables in Java can only be used in conjunction with locks to control the security of concurrent programs accessing competing resources. The condition variable appears for finer control of thread waits and wakes, and before Java5, the wait and wake of the thread depend on the wait () and notify ()/notifyall () Methods of the object objects, so that the processing is not fine-grained. In Java5, a lock can have multiple conditions, each of which can have multiple threads waiting, and by calling the await () method, you can let the thread wait under that condition. When you call the Signalall () method, you can also wake the waiting thread under that condition. Detailed instructions for the condition interface can be specific to the JAVAAPI documentation.

as follows : Public class Testconditon

 Public Static voidMain (string[] args) {//Create a concurrent access accountMyCount MyCount =NewMyCount ("95599200901215522", 10000); //Create a pool of threadsExecutorservice pool = Executors.newfixedthreadpool (3);        #假设改成2会怎么样?? Thread T1=NewSavethread ("Zhang San", MyCount, 1000); Thread T2=NewSavethread ("John Doe", MyCount, 1000); Thread T3=NewDrawthread ("Harry", MyCount, 12600); Thread T4=NewSavethread ("Lao Zhang", MyCount, 600); Thread T5=NewDrawthread ("Lao Niu", MyCount, 1300); Thread T6=NewDrawthread ("Fat", MyCount, 800); Thread T7=NewSavethread ("Test", MyCount, 2100); //Executing individual threadsPool.execute (t1);        Pool.execute (T2);        Pool.execute (T3);        Pool.execute (T4);        Pool.execute (T5);        Pool.execute (T6);        Pool.execute (T7); //Close the thread poolPool.shutdown (); }}/*** Deposit Thread class*/classSavethreadextendsThread {PrivateString name;//Operating Person    PrivateMyCount MyCount;//Account    Private intX//Deposit AmountSavethread (String name, MyCount MyCount,intx) { This. Name =name;  This. MyCount =MyCount;  This. x =x; }     Public voidrun () {mycount.saving (x, name); }}/*** Withdrawal Thread class*/classDrawthreadextendsThread {PrivateString name;//Operating Person    PrivateMyCount MyCount;//Account    Private intX//Deposit AmountDrawthread (String name, MyCount MyCount,intx) { This. Name =name;  This. MyCount =MyCount;  This. x =x; }     Public voidrun () {mycount.drawing (x, name); }}/*** Ordinary bank account, not overdraft*/classMyCount {PrivateString OID;//Account Number    Private intCash//account Balance    PrivateLock lock =NewReentrantlock ();//Account Lock    PrivateCondition _save = Lock.newcondition ();//Deposit Conditions    PrivateCondition _draw = Lock.newcondition ();//Withdrawal ConditionsMyCount (String oid,intCash) {         This. OID =OID;  This. Cash =cash; }    /*** Deposit * *@paramx * Operation amount *@paramName * operator*/     Public voidSaving (intx, String name) {Lock.lock ();//Get lock        if(X > 0) {Cash+ = x;//DepositSYSTEM.OUT.PRINTLN (name + "deposit" + x + ", current balance is" +cash); } _draw.signalall (); //wakes all waiting threads. Lock.unlock ();//Release Lock    }    /*** Withdrawal * *@paramx * Operation amount *@paramName * operator*/     Public voidDrawingintx, String name) {Lock.lock ();//Get lock        Try {             while(Cash-x < 0) {_draw.await ();//Blocking withdrawal operations
SYSTEM.OUT.PRINTLN (name + "in blocking"); } {Cash-= x;//WithdrawalsSYSTEM.OUT.PRINTLN (name + "withdrawal" + x + ", current balance is" +cash); } _save.signalall (); //Wake up all deposit operations}Catch(interruptedexception e) {e.printstacktrace (); } finally{lock.unlock ();//Release Lock } }}

It should be noted that in the design of a shared thread pool, especially to pay attention to the phenomenon of starvation, if there are a large number of consumers so that the producer thread can no longer run, the problem will arise, in the above example, the number of thread pool from 3 to 2 can be found in multiple tests the program hang.

So, we can see that a typical RDBMS system is a variety of threads that perform their duties.

Basic usage and attention points of Java condition conditional variables

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.