Bank withdrawals [Multithreading]{using the re-enter lock lock interface Reentrantlock lock to ensure thread synchronization}

Source: Internet
Author: User
Tags thread class
Classic example: Wife (Juliet) husband (Romeo), using bank cards and passbook, or internet banking, and other security issues for the same account operation.

Here with multi-threaded implementation, while the simulation of the withdrawal of the implementation, using the lock interface Reentrantlock lock to ensure thread synchronization, check the withdrawal security problems, the code is as follows:

--------------------------------------------------------------------------------------------------------------- ---------------------------------

* Thread synchronization: Use the Reentrantlock Lock, write code, and implement thread synchronization
* Reentrantlock has the same concurrency and memory semantics as synchronized (Reentrantlock enables all functions of synchronized with more precise line semantics and better performance)
* Synchronized is implemented at the JVM level, not only through some monitoring tools to monitor the synchronized lock, but also when the code executes an exception, the JVM will automatically release the lock;
* Lock does not automatically release the lock, the lock is implemented by code, to ensure that the lock must be released, you must put unlock () into finally{}
* A java.util.concurrent package has been added in JavaSE5.0 to support synchronization. The Reentrantlock class is a re-entrant, mutex, and lock interface that implements the same basic behavior and semantics as using the Synchronized method, and extends its capabilities
* Applicable: In the case of resource competition is not very intense, synchronized performance is better than Reetrantlock
* The performance of synchronized will be reduced by dozens of times times in the event of intense resource competition, but the performance of Reetrantlock can maintain the normal
*reentrantlock () also has a construction method that can create a fair lock, but it is not recommended because it can significantly reduce the efficiency of the program operation.
*reentrantlock in the transmission of locks, such as "hand-in", more suitable.

--------------------------------------------------------------------------------------------------------------- ---------------------------------

private void Makewithdraw (int amount) {
Add lock
Lock.lock ();
try {
Code
} catch (Interruptedexception e) {
Code
}finally{
Release lock must in the finally
Lock.unlock ();
}
}
Bank Account:

Package Com.tsxs.bank;

public class BankAccount {
	//balance
	private int balance = $;
	Query public
	int getbalance () {
		return banlance;
	}
	Withdrawal public
	void withdraw (int amount) {
		banlance = Banlance-amount;
	}
	Deposit public
	void deposit (int amount) {
		banlance = banlance + amount;
	}
}

using the Reentrantlock lock, the code:

Package com.tsxs.syncmethods;
Import Java.util.concurrent.locks.Lock;

Import Java.util.concurrent.locks.ReentrantLock;
Import Com.tsxs.bank.BankAccount; /** * This thread class implements runnable interface <br/> * thread synchronization: Using Reentrantlock Lock, code authoring, Implementing thread synchronization <br/> * Reentrantlock having the same concurrency as synchronized and memory semantics (Reentrantlock can achieve all the functions of synchronized, with more precise line semantics and better performance). <br/> * Synchronized is implemented at the JVM level, and not only can monitor synchronized locks through some monitoring tools, but exceptions occur when code executes, and the JVM automatically releases the lock; * Lock does not automatically release the lock. Lock is implemented by code, and unlock () must be placed in finally{} to ensure that the lock is bound to be released.
 &LT;BR/> * Applicable: In the case of resource competition is not very intense, synchronized performance is better than Reetrantlock.
 * The performance of synchronized will be reduced by dozens of times times in the event of intense resource competition, but the performance of the Reetrantlock can be maintained as usual, <br/> *lock in the lock such as the transmission lock, such as "hand-holding", more suitable.  * */public class Codelock implements runnable{//all thread multithreaded threads share Runnable (interface object) and account object Private BankAccount account =
	New BankAccount ();
	Declaration Lock, jdk1.5 lock lock = new Reentrantlock ();			@Override public void Run () {for (int i = 0; i< 5; i++) {//Total withdrawals 5 times makewithdraw (100); Each withdrawal of the IF (Account.getbalance () &LT
	
	0) {System.out.println ("☆" +thread.currentthread (). GetName () + "Overdrawn!");}} /** * Makewithdraw Account Withdrawal * @param amount Withdrawal amount <br/> * Print log record withdrawal process * */private void Makewithdraw (int amount)
		{//add lock Lock.lock (); try {if (account.getbanlance () >= amount) {//If the balance is sufficient then the withdrawal System.out.println ("☆" +thread.currentthread (). GetName ()
				+ "Ready to withdraw money!");
				Thread.Sleep (500);
				Account.withdraw (amount);			SYSTEM.OUT.PRINTLN ("☆" +thread.currentthread (). GetName () + "complete" +amount+ "withdrawals with a balance of" +account.getbalance ()); }else{//Insufficient balance will prompt System.out.println ("☆" + "balance is not enough to pay" +thread.currentthread (). GetName () +amount+ "withdrawals with a balance of" +account.getb
			Alance ()); }} catch (Interruptedexception e) {System.out.println (Thread.CurrentThread (). GetName () + "ready to withdraw, wait for 0.5s thread to break!"
		+e.getmessage ());
		}finally{//release Lock must in the finally Lock.unlock (); }
	}
}

Test code:

Package com.tsxs.test;

Import Org.junit.Test;

Import Com.tsxs.syncmethods.CodeLock;
Import Com.tsxs.syncmethods.NoSync;
Import Com.tsxs.syncmethods.SyncBlock;
Import Com.tsxs.syncmethods.SyncMethod;

public class Treadsynctest {

//	@Test
//Public	void Test () {
/*junit is not suitable for multithreaded concurrency testing.
    because the thread is still in the active state, JUnit has performed the completion.
	in JUnit's Testrunner, it is not designed to search for runnable instances,
	and waits for those threads to report, it simply executes them and ignores their existence.
	in summary, it is not possible to write and maintain multithreaded unit tests in JUnit.
}*/public	
	static void Main (string[] args) {
		//implement runnable: All thread threads are shared runnable (interface object)
//		NoSync target =new NoSync ();		Syncmethod target = new Syncmethod ();		syncblock target = new SyncBlock ();
		Codelock target = new Codelock ();
		Create Li Qi and his wife two threads implement the withdrawal (at the same time)
		thread LQ = new thread (target);
		Lq.setname ("Romeo");
		Thread LQWF = new Thread (target);
		Lqwf.setname ("Juliet");
		Call the Start () method of the Thread object, start the thread, execute the Run () method (OS)
		Lq.start ();
		Lqwf.start ();
	}
}


Test results:

☆ Romeo ready to withdraw!
☆ Romeo complete 100 withdrawals! Balance is 400
☆ Romeo ready to withdraw!
☆ Romeo complete 100 withdrawals! Balance is 300
☆ Juliet ready to withdraw!
☆ Juliet Complete 100 withdrawals! Balance is 200
☆ Juliet ready to withdraw!
☆ Juliet Complete 100 withdrawals! Balance is 100
☆ Juliet ready to withdraw!
☆ Juliet Complete 100 Withdrawals! Balance is 0
☆ The balance is not enough to pay Juliet 100 withdrawal, the balance is 0
☆ The balance is not enough to pay Juliet 100 withdrawal, the balance is 0
☆ The balance is not enough to pay Romeo 100 withdrawal, the balance is 0
☆ The balance is not enough to pay Romeo 100 withdrawal, the balance is 0
☆ The balance is not enough to pay Romeo 100 withdrawal, the balance is 0

Analysis results:

A total of 10 withdrawals from the two threads account for a total of $.

withdrawal Results: Under multi-threaded access, the total amount of successful withdrawals is 500, and other withdrawals, the correct information.

Multi-threaded access security assurance.

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.