Java multithreading-new features-locks

Source: Internet
Author: User
Tags cas

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.

Package Cn.thread;import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;import Java.util.concurrent.locks.lock;import java.util.concurrent.locks.reentrantlock;/** * * * @author 林计钦 * @version 1.0 201 3-7-25 am 10:33:37 */public class Locktest {public static void main (string[] args) {locktest test = new Locktes        T ();        Create a concurrent access account MyCount MyCount = test.new MyCount ("95599200901215522", 10000);        Create a Lock object lock lock = new Reentrantlock ();        Create a thread pool executorservice pool = Executors.newcachedthreadpool ();        Create some concurrent access users, a credit card, save, take the take, good lively ah user U1 = Test.new User ("Zhang San", MyCount, -4000, lock);        User U2 = Test.new user ("Zhang San his father", MyCount, 6000, lock);        User U3 = Test.new User ("Zhang three younger brother", MyCount, -8000, lock);        User U4 = Test.new user ("Zhang San", MyCount, +, lock);        Perform individual user operations Pool.execute (U1) in the thread pool;        Pool.execute (U2);        Pool.execute (U3);        Pool.execute (U4); //close 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 Lock myLock;            The lock object required to perform the operation User (String name, MyCount MyCount, int iocash, lock myLock) {this.name = name;            This.mycount = MyCount;            This.iocash = Iocash;        This.mylock = MyLock;            public void Run () {string string;            if (iocash>0) {string= "deposit";            }else{string= "withdrawals";            }//Get lock Mylock.lock (); Execute cash Business System.out.println (name + "in action" + MyCount + "account," + string+ "amount for" + Iocash + ", current            The amount is "+ Mycount.getcash ()");            Mycount.setcash (Mycount.getcash () + Iocash); SYSTEM.OUT.PRINTLN (name + "operation" + MyCount + "account success," + String + "amount is" + Iocash + ", the current amount is" + mycount.getcash ());            System.out.println ("============");        Release the lock, or else the thread does not have the opportunity to execute the mylock.unlock (); }}/** * Credit card account, can overdraft * * Class MyCount {private String oid;//account private int cash;//Account remainder            Amount 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{" + "account = '" + oid + ' \ ' + ", balance =" + cash +        ‘}‘; }    }}
Zhang San is operating the mycount{account = ' 95599200901215522 ', the balance = 10000} account, the withdrawal amount is-4000, the current amount is 10000 three operations mycount{account = ' 95599200901215522 ', balance = 6000} The account is successful, the withdrawal amount is-4000, the current amount is 6000============ Zhang three brother is operating mycount{account = ' 95599200901215522 ', balance = 6000} account, withdrawal amount is-8000, The current amount is 6000 three brother operation mycount{account = ' 95599200901215522 ', Balance =-2000} account success, withdrawal amount is-8000, the current amount is -2000============ Zhang three his father is operating mycount{ account = ' 95599200901215522 ', Balance =-2000} account, deposit amount is 6000, current amount is-2000 three father operation mycount{account = ' 95599200901215522 ', balance = 4000} account successful, The deposit amount is 6000, the current amount is 4000============ Zhang San is operating mycount{account = ' 95599200901215522 ', the balance = 4000} account, the deposit amount is 800, the current amount is 4000 three operations mycount{ account = ' 95599200901215522 ', balance = 4800} account successful, deposit 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.

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

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.