Java multithreading-New features-locks (top)

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.

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.

Java multithreading-New features-locks (top)

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.