Lock synchronization lock -- thread synchronization, Lock synchronization -- thread

Source: Internet
Author: User

Lock synchronization lock -- thread synchronization, Lock synchronization -- thread
Lock-synchronization Lock

Lock is a powerful thread synchronization mechanism provided by Java 5-achieve synchronization by displaying and defining synchronization Lock objects. Locks and locks that can be displayed. Only one thread can lock the lock object at a time.

Lock ReadLock, WriteLock, ReentrantLock (reentrant Lock)

ReentrantLock is commonly used. The Code is as follows:

Code logic: Account class, synchronous method for obtaining money, DrawThread for obtaining money

Account:

Package lock. reentrantlock2; import java. util. concurrent. locks. *;/*** Account class, which must be synchronized */public class Account {// defines the lock Object private final ReentrantLock lock = new ReentrantLock (); private String accountNo; private double balance; public Account () {} public Account (String accountNo, double balance) {this. accountNo = accountNo; this. balance = balance;} public void setAccountNo (String accountNo) {this. accountNo = accountNo;} Public String getAccountNo () {return this. accountNo;} public double getBalance () {return this. balance;} public void draw (double drawAmount) {lock. lock (); try {// the account balance is greater than the amount of money withdrawn if (balance> = drawAmount) {// spit out the bill System. out. println (Thread. currentThread (). getName () + "money Acquisition successful! Spit out money: "+ drawAmount); try {Thread. sleep (1);} catch (InterruptedException ex) {ex. printStackTrace ();} // modify balance-= drawAmount; System. out. println ("\ t balance:" + balance);} else {System. out. println (Thread. currentThread (). getName () + "failed to get money! Insufficient balance! ") ;}} Finally {lock. unlock () ;}} public int hashCode () {return accountNo. hashCode ();} public boolean equals (Object obj) {if (obj! = Null & obj. getClass () = Account. class) {Account target = (Account) obj; return target. getAccountNo (). equals (accountNo);} return false ;}}

DrawThread:

Package lock. reentrantlock2;/*** call the account to get the money **/public class DrawThread extends Thread {// simulate the user Account private account; // The amount of money that the current withdrawal thread wants to fetch private double drawAmount; public DrawThread (String name, Account account Account, double drawAmount) {super (name); this. account = account; this. drawAmount = drawAmount;} // when multiple threads modify the same shared data, data security issues are involved. Public void run () {account. draw (drawAmount );}}

TestDraw:

Package lock. reentrantlock2;/***/public class TestDraw {public static void main (String [] args) {// create an Account acct = new Account ("1234567", 1000 ); // simulate two threads to get money from the same account new DrawThread ("A", acct, 800 ). start (); new DrawThread ("B", acct, 800 ). start ();}}

Running result:

A successfully obtained the money! Spit out money: 800.0
Balance: 200.0
B failed to get the money! Insufficient balance!

 

The Lock synchronization method is similar to the synchronization method. It is a "Lock-modify public variables-release Lock" mode, and the code is easy to understand. The two threads correspond to one Account object, which ensures that the two threads correspond to one lock object and that only one thread enters the critical section at the same time. Lock also contains lockInterruptibly () that is too easy to Lock, attempts to obtain the lockInterruptibly () that can interrupt the Lock, and methods such as tryLock (long, TimeUnit) that obtain the time-out failure Lock.

The ReentrantLock lock can be reentrant to lock the locked ReentrantLock again. After each thread calls lock (), it must display the call of unlock to release the lock, several locks correspond to several unlocks. In addition, the unlock is placed in the finally code block. When an exception occurs, the Lock is not released, so it is safer to release the Lock in finally.

Just a brief description of Lock, laying the foundation for the next thread communication.

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.