java--bank deposit and withdrawal thread design 2 (thread mutex) __ Thread

Source: Internet
Author: User

Synchronization: The concept of object locks. If multiple threads share an object, the operating system generates a lock for each object with one word, and the lock and object one by one correspond. If a thread wants to manipulate an object, it must get the lock on the object.
Lock: Synchronous Statement or synchronization method (a synchronous statement is used here). Resolves an interaction thread with time-related errors.
Note: The mutex must be the same object or it cannot be locked.

public class Save extends thread{
    private account A;
    private double value;

    Public Save (account A, double value) {
        this.a = A;
        This.value = value;
    }

    public void Run () {
        synchronized (a) {
            double b = a.getbalance ();
            A.put (value);
            System.out.println (A.getname () + "account, existing" + B + ", deposit" + value
                    + ", balance" + a.getbalance ());}}
Package cn.hncu.thread.motion;

public class Fetch extends thread{
    private account A;
    private double value;

    Public fetch (account A, double value) {
        this.a = A;
        This.value = value;
    }

    public void Run () {
        synchronized (a) {//holding lock
            double b = a.getbalance ();
            System.out.println (A.getname () + "account, existing" + B + ", remove" + a.get (value)
                    + ", balance" + a.getbalance ());
        } Unlock after a sync statement
Package cn.hncu.thread.motion;

public class Bank {public

    static void Main (string[] args) {

//account      a1=new account ("Wang");      Save S1=new Save (a1,100);      Save S1=new Save (new account ("Wang");      S1.start ();
        Account a1=new account ("Wang");
        New Save (a1,100). Start ();
        New Save (a1,200). Start ();
        New Fetch (A1,300). Start ();

        New Save (New account ("Xu"). Start ();
    }


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.