In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article is about how Java uses synchronization to solve the security problems of bank withdrawals. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
The details are as follows:
A little bit of eye contact
Corresponding to synchronous code blocks, Java's multithreaded safety support also provides synchronization methods, which are called synchronization methods by decorating a method with the synchronized keyword. For synchronized-decorated instance methods (non-static methods), there is no need to display the specified synchronization monitor, which is this, that is, the object that calls the method.
Thread-safe classes can be easily implemented by using synchronization methods, and thread-safe classes have the following characteristics.
Objects of this class can be safely accessed by multiple threads. Each thread will get the correct result after calling any method of the object. After each thread calls any method of the object, the state of the object remains reasonable.
An immutable class is always thread-safe because its object state is immutable; but mutable objects need additional methods to keep them thread-safe.
Two code
1 define an account class
Public class Account {/ / encapsulates two member variables, private String accountNo; private double balance; public Account () {} / / Constructor public Account (String accountNo, double balance) {this.accountNo = accountNo; this.balance = balance;} / / accountNo's setter and getter method public void setAccountNo (String accountNo) {this.accountNo = accountNo;} public String getAccountNo () {return this.accountNo } / / therefore, the account balance is not allowed to be modified casually, so only the getter method is provided for balance, and public double getBalance () {return this.balance;} / / provides a thread-safe draw () method to complete the withdrawal operation public synchronized void draw (double drawAmount) {/ / account balance is greater than the number of withdrawals if (balance > = drawAmount) {/ / spit out banknotes System.out.println (Thread.currentThread (). GetName () + "money withdrawal is successful! Spit out banknotes: "+ drawAmount); try {Thread.sleep (1);} catch (InterruptedException ex) {ex.printStackTrace ();} / / modify the balance balance-= drawAmount; System.out.println ("\ t balance: "+ balance);} else {System.out.println (Thread.currentThread (). GetName () +" failed to withdraw money! Insufficient balance! ") ;}} / / the following two methods override hashCode () and equals () method public int hashCode () {return accountNo.hashCode ();} public boolean equals (Object obj) {if (this = = obj) return true; if (obj! = null & & obj.getClass () = Account.class) {Account target = (Account) obj; return target.getAccountNo (). Equals (accountNo);} return false;}}
2 define a money withdrawal thread
Public class DrawThread extends Thread {/ / simulate user account private Account account; / / the amount of money that the current withdrawal thread wants to withdraw private double drawAmount; public DrawThread (String name, Account account, double drawAmount) {super (name); this.account = account; this.drawAmount = drawAmount;} / / when multiple threads modify the same shared data, data security issues will be involved. Public void run () {/ / the synchronization monitor that directly calls the draw method of the account object to execute the withdrawal / / synchronization method is the object on behalf of this,this that calls the draw () method. / / that is, before a thread enters the draw () method, it must lock the account object. Account.draw (drawAmount);}}
3 test the main class
Public class DrawTest {public static void main (String [] args) {/ / create an account Account acct = new Account ("1234567", 1000); / / simulate two threads to withdraw money from the same account new DrawThread ("A", acct, 1000). Start (); new DrawThread ("B", acct, 800). Start ();}}
Three running results
B succeeded in withdrawing money! Spit out banknotes: 800.0 balance: 200.0 A failed to withdraw money! Sorry, your credit is running low!
Four instructions
The main results are as follows: 1 the draw () method of code withdrawal is added, and the method is modified with the synchronized keyword to turn the method into a synchronization method. The synchronization monitor of the synchronization method is this, so for the same Account account, only one thread can obtain the lock on the Account object at any time, and then enter the draw () method to perform the money withdrawal operation-- which can also ensure the thread safety of multiple threads withdrawing money concurrently.
(2) the thread safety of variable classes is at the cost of reducing the running efficiency of the program. In order to reduce the negative impact of thread safety, the program can adopt the following strategies:
Do not synchronize all methods of thread-safe classes, only those that change competing resources (that is, shared resources). For example, the accountNo instance variable in the Account class above does not need to be synchronized, so the program only synchronizes the draw () method. If a mutable class has two runtime environments: single-threaded and multithreaded, you should provide two versions of the mutable class, thread-safe and thread-unsafe. Use a thread-unsafe version to ensure performance in a single-threaded environment and a thread-safe version in a multithreaded environment.
3 the StringBuilder and StringBuffer provided by JDK are designed to take care of the classes provided in single-threaded and multithreaded environments. StringBuilder classes should be used to ensure good performance in single-threaded environments, and StringBuffer should be used when multithreaded safety is needed.
Thank you for reading! This is the end of the article on "how Java uses synchronization to solve the security problem of bank withdrawal". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it out for more people to see!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.