Java multithreading-new features-locks

Source: Internet
Author: User

Java read-write lock has an interface Java.util.concurrent.locks.ReadWriteLock, there are specific implementation Reentrantreadwritelock, detailed API can view JAVAAPI document.

The following example is based on the text example, the general lock to read and write locks, and add the account balance query function, the code is as follows:

PackageCn.thread;ImportJava.util.concurrent.ExecutorService;ImportJava.util.concurrent.Executors;ImportJava.util.concurrent.locks.ReadWriteLock;ImportJava.util.concurrent.locks.ReentrantReadWriteLock;/*** Read/write lock * *@authorLin Yi-chin *@version1.0 2013-7-25 10:33:37*/PublicClasswritereadlocktest {PublicStaticvoidMain (string[] args) {writereadlocktest test =NewWritereadlocktest ();//Create a concurrent access account MyCount MyCount = Test.New MyCount ("95599200901215522", 10000);//Create a Lock object readwritelock lock =New Reentrantreadwritelock (False);//Create a thread pool executorservice pool = Executors.newfixedthreadpool (2);//Create some concurrent access users, a credit card, storage, fetch, good lively ah user u1 = test.New User ("Zhang San", MyCount, -4000, Lock,False); User u2 = Test.New User ("Three daddies", MyCount, 6000, lock,False); User U3 = Test.New User ("Three brothers", MyCount, -8000, Lock,False); User U4 = Test.New User ("Zhang San", MyCount, +, lock,False); User U5 = Test.New User ("Three daddies", MyCount, 0, lock,True);//Perform actions for individual users in the thread poolPool.execute (U1); Pool.execute (U2); Pool.execute (U3); Pool.execute (U4); Pool.execute (U5);//Close the thread poolPool.shutdown (); }/*** Credit card users*/Class UserImplementsRunnable {private String name;//User namePrivate MyCount MyCount;//The account to be operated onPrivateint Iocash;//The amount of the operation, of course, has a positive or negative pointPrivate Readwritelock MyLock;//The lock object required to perform the operationPrivateBoolean Ischeck;//Whether to queryUser (String name, MyCount MyCount,int Iocash, Readwritelock myLock,BooleanIscheck) {THIS.name =NameThis.mycount =MyCount;This.iocash =Iocash;This.mylock =MyLock;This.ischeck =Ischeck; }PublicvoidRun () {If(Ischeck) {//Get read lockMylock.readlock (). Lock (); System.out.println ("read:" + name + "Querying" + MyCount + "account with current Amount" +Mycount.getcash ());//Release Read lockMylock.readlock (). Unlock (); }Else{//Get write LockMylock.writelock (). Lock ();//Execute Cash Business System.out.println ("write:" + name + "in action" + MyCount + "account, amount =" + Iocash + ", Current amount is" + "Mycount.getcash ()); Mycount.setcash (Mycount.getcash () +Iocash); System.out.println ("write:" + name + "Action" + MyCount + "account successful, the amount is" + Iocash + ", the current amount is" +Mycount.getcash ());//Release Write lockMylock.writelock (). Unlock (); } } }/*** Credit Card account can be overdrawn at will*/ClassMyCount {Private String oid;//AccountPrivateint cash;//Account balanceMyCount (String OID,IntCash) {This.oid =OIdThis.cash =Cash }PublicString getoid () {ReturnOId }public void Setoid ( String oid) {this.oid = oid;} public int GetCash () { Return cash;} public void Setcash ( Int Cash) {this.cash =public String toString () {return "mycount{" + "oid=" "+ oid +" \ "+", cash= "+ Cash + '} ' ;}}    
 write: Zhang San is operating mycount{oid= ' 95599200901215522 ', cash=10000} account with an amount of -4000} account with an amount of 6000, The current amount is 6000 write: Zhang San his father Operation Mycount{oid= ' 95599200901215522 ', Cash=12000} The account is successful, the amount is 6000, The current amount is 12000 write: Zhang San is operating mycount{oid= ' 95599200901215522 ', Cash=12000} account with an amount of 800, The current amount is 12000 write: Zhang San operation mycount{oid= ' 95599200901215522 ', Cash=12800} The account is successful, the amount is 800, The current amount is 12800 write: Zhang San his brother is operating mycount{oid= ' 95599200901215522 ', cash=12800} account with an amount of -8000     

In practical development, it is best to use read and write locks in the case of read and write locks, rather than ordinary locks, in order to better performance.

Java multithreading-new features-locks

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.