Java line assigns feature---Lock

Source: Internet
Author: User

In Java5, the lock object is specially provided, and the lock can be used to control the concurrent access of competing resources, which is mainly concentrated under the Java.util.concurrent.locks package, which has three important interfaces condition, Lock, Readwritelock.

Condition

Condition the object monitor method (wait, notify, and Notifyall) into distinct objects to provide multiple wait set (Wait-set) for each object by combining these objects with any lock implementation.

Lock

The lock implementation provides a wider range of locking operations than is possible with synchronized methods and statements.

Readwritelock

Readwritelock maintains a pair of related locks, one for read-only operations and the other for write operations.

About the introduction of the lock, the API documentation a lot of explanations, look very annoying, or look at an example of the document is easier to understand.

/*** Java Thread: Lock **/ Public classTest { Public Static voidMain (string[] args) {//Create a concurrent access accountMyCount MyCount =NewMyCount ("95599200901215522", 10000); //Create a Lock objectLock lock =NewReentrantlock (); //Create a pool of threadsExecutorservice pool =Executors.newcachedthreadpool (); //create some concurrent access users, a credit card, save, take the take, good lively ahUser u1 =NewUser ("Zhang San", MyCount,-4000, lock); User U2=NewUser ("Three Fathers", MyCount, 6000, lock); User U3=NewUser ("Three brothers", MyCount, 8000, lock); User U4=NewUser ("Zhang San", MyCount, 800, lock); //perform actions for individual users in the thread poolPool.execute (U1);        Pool.execute (U2);        Pool.execute (U3);        Pool.execute (U4); //Close the thread poolPool.shutdown (); }}/*** Credit card users*/classUserImplementsRunnable {PrivateString name;//User name    PrivateMyCount MyCount;//The account to be operated on    Private intIocash;//The amount of the operation, of course, has a positive or negative point    PrivateLock MyLock;//the lock object required to perform the OperationUser (String name, MyCount MyCount,intIocash, Lock myLock) {         This. Name =name;  This. MyCount =MyCount;  This. Iocash =Iocash;  This. MyLock =MyLock; }     Public voidrun () {//Get lockMylock.lock (); //execution of cash operationsSYSTEM.OUT.PRINTLN (name + "operating" + MyCount + "account, amount is" + Iocash + ", Current amount is" + "Mycount.getcash ()); Mycount.setcash (Mycount.getcash ()+Iocash); SYSTEM.OUT.PRINTLN (Name+ "Operation" + MyCount + "account success, the amount is" + Iocash + ", the current amount is" +Mycount.getcash ()); //release the lock, or else the thread will not be able to execute theMylock.unlock (); }}/*** Credit Card account can be overdrawn at will*/classMyCount {PrivateString OID;//Account Number    Private intCash//account BalanceMyCount (String oid,intCash) {         This. OID =OID;  This. Cash =cash; }     PublicString getoid () {returnOID; }     Public voidsetoid (String oid) { This. OID =OID; }     Public intGetCash () {returncash; }     Public voidSetcash (intCash) {         This. Cash =cash; } @Override PublicString toString () {return"mycount{" + "oid=" + oid + ' \ ' + ", cash=" + Cash + '} '; }}

The output results are as follows:

Zhang San is operating mycount{oid= ' 95599200901215522 ', cash=10000} account, the amount is-4000, the current amount is 10000
Zhang San operation mycount{oid= ' 95599200901215522 ', cash=6000} account successful, amount is-4000, current amount is 6000
Zhang San his brother is operating mycount{oid= ' 95599200901215522 ', cash=6000} account, the amount is-8000, the current amount is 6000
Zhang San his brother Operation Mycount{oid= ' 95599200901215522 ', cash=-2000} account success, amount is-8000, the current amount is 2000
Zhang San his father is operating mycount{oid= ' 95599200901215522 ', cash=-2000} account, the amount is 6000, the current amount is 2000
Zhang San his father Operation Mycount{oid= ' 95599200901215522 ', cash=4000} account success, the amount is 6000, the current amount is 4000
Zhang San is operating mycount{oid= ' 95599200901215522 ', cash=4000} account, the amount is 800, the current amount is 4000
Zhang San operation mycount{oid= ' 95599200901215522 ', cash=4800} account successful, amount is 800, current amount is 4800

As you can see from the above output, it is much easier to use lock objects than to use locks directly on an unsuspecting object.

It is important to note, however, that after the lock object is acquired, the lock should be released as soon as possible so that other threads waiting for the lock have an opportunity to execute.

< pick:http://www.cnblogs.com/riskyer/p/3263032.html>

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:

/*** Java Thread: Lock **/ Public classTest { Public Static voidMain (string[] args) {//Create a concurrent access accountMyCount MyCount =NewMyCount ("95599200901215522", 10000); //Create a Lock objectReadwritelock lock =NewReentrantreadwritelock (false); //Create a pool of threadsExecutorservice pool = Executors.newfixedthreadpool (2); //create some concurrent access users, a credit card, save, take the take, good lively ahUser u1 =NewUser ("Zhang San", MyCount, -4000, Lock,false); User U2=NewUser ("Zhang Sam", MyCount, 6000, lock,false); User U3=NewUser ("Zhang three younger brother", MyCount, -8000, Lock,false); User U4=NewUser ("Zhang San", MyCount, +, lock,false); User U5=NewUser ("Three Fathers", 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*/classUserImplementsRunnable {PrivateString name;//User name    PrivateMyCount MyCount;//The account to be operated on    Private intIocash;//The amount of the operation, of course, has a positive or negative point    PrivateReadwritelock MyLock;//the lock object required to perform the Operation    Private BooleanIscheck;//whether to queryUser (String name, MyCount MyCount,intIocash, Readwritelock MyLock,BooleanIscheck) {         This. Name =name;  This. MyCount =MyCount;  This. Iocash =Iocash;  This. MyLock =MyLock;  This. Ischeck =Ischeck; }     Public voidrun () {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 (); //execution of cash operationsSystem.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 successful, amount is" + Iocash + ", Current amount is" + "Mycount.getcash ()); //Release Write lockmylock.writelock (). Unlock (); }    }}/*** Credit Card account can be overdrawn at will*/classMyCount {PrivateString OID;//Account Number    Private intCash//account BalanceMyCount (String oid,intCash) {         This. OID =OID;  This. Cash =cash; }     PublicString getoid () {returnOID; }     Public voidsetoid (String oid) { This. OID =OID; }     Public intGetCash () {returncash; }     Public voidSetcash (intCash) {         This. Cash =cash; } @Override PublicString toString () {return"mycount{" + "oid=" + oid + ' \ ' + ", cash=" + Cash + '} '; }}

The results of the implementation are as follows:

Write: Zhang San his father is operating mycount{oid= ' 95599200901215522 ', cash=10000} account, the amount is 6000, the current amount is 10000
Write: Zhang San his father Operation Mycount{oid= ' 95599200901215522 ', cash=16000} account success, the amount is 6000, the current amount is 16000
Write: Zhang San is operating mycount{oid= ' 95599200901215522 ', cash=16000} account, the amount is-4000, the current amount is 16000
Write: Zhang San operation mycount{oid= ' 95599200901215522 ', cash=12000} account successful, amount is-4000, 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, 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 success, the amount is 8000, the current amount is 4800
Read: Zhang San his father is inquiring mycount{oid= ' 95599200901215522 ', cash=4800} account, the 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 line assigns feature---Lock

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.