Java multithreading-New features-locks (bottom)

Source: Internet
Author: User
Tags cas

The lock interface as well as the object is mentioned above, and it is very graceful to control the secure access of competing resources, but this kind of lock does not distinguish between read and write, which is called normal lock. In order to improve performance, Java provides read and write locks, read locks are used where they are written, write locks are used in the writing, flexible control, to a certain extent, improve the execution efficiency of the program.

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:

Package Cn.thread;import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;import Java.util.concurrent.locks.readwritelock;import java.util.concurrent.locks.reentrantreadwritelock;/** * Read/write lock * * @ Author Lin Yi-chin * @version 1.0 2013-7-25 a.m. 10:33:37 */public class Writereadlocktest {public static void main (string[] args        ) {writereadlocktest test = new Writereadlocktest ();        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 ("Zhang San his father", MyCount, 6000, lock, false);        User U3 = Test.new User ("Zhang three younger brother", MyCount, -8000, lock, false);        User U4 = Test.new user ("Zhang San", MyCount, +, lock, false); User U5 = Test.new user ("Zhang SanHis father ", MyCount, 0, lock, true);        Perform individual user operations Pool.execute (U1) in the thread pool;        Pool.execute (U2);        Pool.execute (U3);        Pool.execute (U4);        Pool.execute (U5);    Close the thread pool Pool.shutdown ();  }/** * Credit card User */class user implements Runnable {private String name;//user name Private MyCount MyCount; The account you want to operate private int iocash; Operation of the amount, of course there are positive and negative points of the private readwritelock myLock; The lock object required to perform the operation private Boolean ischeck; Whether to query User (String name, MyCount MyCount, int iocash, Readwritelock myLock, Boolean ischeck) {This.nam            e = name;            This.mycount = MyCount;            This.iocash = Iocash;            This.mylock = MyLock;        This.ischeck = Ischeck;                public void Run () {if (Ischeck) {//gets read lock Mylock.readlock (). Lock ();             System.out.println ("read:" + name + "Querying" + MyCount + "account, current amount is" + mycount.getcash ());   Release read lock Mylock.readlock (). Unlock ();                } else {//Get write lock Mylock.writelock (). Lock ();                        Execute Cash Business System.out.println ("write:" + name + "Operating" + MyCount + "account, amount is" + Iocash + ", Current amount is"                + Mycount.getcash ());                Mycount.setcash (Mycount.getcash () + Iocash); System.out.println ("write:" + name + "Action" + MyCount + "account is successful, the amount is" + Iocash + ", the current amount is" + Mycount.getcash "(                ));            Release write lock Mylock.writelock (). Unlock (); }}}/** * Credit card account, can overdraft * * Class MyCount {private String oid;//account private int CAs H            Account balance MyCount (String oid, int cash) {this.oid = oid;        This.cash = cash;        } public String getoid () {return OID;        } public void Setoid (String oid) {this.oid = oid;          } public int GetCash () {  return cash;        } public void Setcash (int cash) {This.cash = cash; } @Override Public String toString () {return "mycount{" + "oid= '" + oid + ' \ ' + ", cash=" + CAs        H + '} '; }    }}
Write: Zhang San is operating mycount{oid= ' 95599200901215522 ', cash=10000} account, the amount is-4000, the current amount is 10000 write: Zhang San operation mycount{oid= ' 95599200901215522 ' , cash=6000} account success, the amount is-4000, the current amount is 6000 write: Zhang San his father is operating mycount{oid= ' 95599200901215522 ', cash=6000} account, the amount is 6000, The current amount is 6000 write: Zhang San his father Operation Mycount{oid= ' 95599200901215522 ', cash=12000} account success, the amount is 6000, the current amount is 12000 write: Zhang San is operating mycount{oid= ' 95599200901215522 ', cash=12000} account, the amount is 800, the current amount is 12000 write: Zhang San operation mycount{oid= ' 95599200901215522 ', cash=12800} account successful, amount is 800 , the current amount is 12800 write: Zhang San his brother is operating mycount{oid= ' 95599200901215522 ', cash=12800} account, the amount is 8000, the current amount is 12800 write: Zhang San his brother Operation Mycount{oid= ' 95599200901215522 ', cash=4800} account successful, the amount is 8000, the current amount is 4800 read: Zhang San his father is querying mycount{oid= ' 95599200901215522 ', cash=4800} account, Current amount is 4800

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 (bottom)

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.