Java multi-threading learning --synchronized lock mechanism

When using Java synchronization lock mechanism in multiple threads, locks must pay attention to the object, the following example is not a lock on the object

Example: two-man operation with a bank account, her husband operate in the ATM machine at the bank counter operations wife

Account type: There are one million accounts

public class Acount {
    public int money=100;
}

ATM machine classes: presence of a number of objects and Acount to take the money inside, added in the process takeMoney synchronized mechanism

public class ATM implements Runnable{
    private Acount acount;
    private int withdrawMoney;

    public ATM(Acount acount, int withdrawMoney) {
        this.acount = acount;
        this.withdrawMoney = withdrawMoney;
    }

    @Override
    public void run() {
        takeMoney();
    }

    public synchronized void takeMoney(){    //取钱
        if(acount.money<withdrawMoney){
            return; 
        } 
        The try { 
            the Thread.sleep ( 200 is);   // Sleep after entering thread 1, thread 2 can still come in, which could cause a deficit 
        } the catch (InterruptedException E) { 
            e.printStackTrace (); 
        } 
        System.out.println (the Thread . .currentThread () getName () + "taken" + withdrawMoney + "ten thousand yuan" ); 
        acount.money - = withdrawMoney; 
        System.out.println ( "account balance:" + acount.money); 
    } 
}

Customer class: create a unique account, two ATM machines (one analogue counter), respectively, for two people to use

public  class the Customer {
     public  static  void main (String [] args) { 
        Acount acount = new new Acount (); 
        ATM ATM1 = new new ATM (acount, 70);     // husband in the ATM operating account, his wife operation account counter 
        ATM ATM2 = new new the ATM (acount, 80 ); 
        the Thread husband = new new the Thread (ATM1, "husband" ); 
        the Thread wife = new new the Thread (ATM2, "wife" ); 

        husband.start (); 
        wife.start (); 
    } 
}

operation result:

You can see the addition of synchronized still occurs after thread-safe.

Analysis: the synchronized mechanism is generally used in the operation of the data object, the method is a method belonging takeMoney ATM machine, in this example, there are a total of account class, class two ATM machines, ATM machines two classes to account class operations , so we should lock the account type.

 

Guess you like

Origin www.cnblogs.com/chiweiming/p/11109078.html
Recommended