why doesn't this synchronized method work as expected?

后端 未结 3 938
一向
一向 2020-12-20 17:45

I have a class called \"Account\"

public class Account {

    public double balance = 1500;

    public synchronized double withDrawFromPrivateBalance(double         


        
3条回答
  •  忘掉有多难
    2020-12-20 18:20

    Your private synchronized void find() method is synchronizing on different locks. Try synchronizing it on same objects like

    private void find(){
        synchronized(myTargetAccount){
            localBalance = myTargetAccount.balance;
            System.out.println(getName() + ": local balance = " + localBalance);
            localBalance -= 100;
            myTargetAccount.balance =  localBalance;
        }
    }
    

    You can also make your Account class more thread safe, by making its fields private and adding synchronized modifier to all its getters and setters and then use only this methods to change value of fields.

提交回复
热议问题