Synchronized solve the problem of bank withdraw money __java

Source: Internet
Author: User
when multiple threads simultaneously access a common resource and make modifications, an error occurs, such as the question of the bank taking money: Create a new Acount.java to encapsulate bank accounts and balances, as follows:

A new Firstthread.java is created to represent the current thread:
Run results, the account balance will appear negative, it is obvious, when one of the threads to withdraw money, another thread also take money, the results are as follows:

At this time should be the account acount lock, that is, the use of the Synchronized keyword, after the lock, when the cable access, will acquire a lock, and its resources to modify operations, other threads only when the thread has been modified and release the lock to access it, This locking--modification--the mode of releasing locks solves the error caused by multiple threads modifying resources at the same time. in the code on the Fristthread.java diagram, remove 11 lines and 27 lines of comments, which run as follows:

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.