Java sychronized 不保护变量

Java sychronized not protecting the variable

我正在学习 Java 多线程。这是我写的代码。

package com.company;


public class Account  {
    private double balance = 100;

    public synchronized double getBalance() {
        synchronized (this){
            return balance;
        }
    }

    public  void setBalance(double balance) {
        this.balance = balance;
    }
    public   boolean withdraw(double amount,String name){
        if(this.getBalance()>amount){
            if(Thread.currentThread().getName().equals("customer0")){
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            this.setBalance(this.getBalance() - amount);
            System.out.println(Thread.currentThread().getName() + " withdraw " + amount);
            System.out.println("Hello,  " + Thread.currentThread().getName() + " You current balance is " + this.getBalance());

            return true;
        }
        else{
            System.out.println("Sorry, " + Thread.currentThread().getName() + ". Your current balance is " + this.getBalance() + " and you  cannot withdraw " + amount);
            //System.out.println("Welcome,  " + Thread.currentThread().getName() + " Your current balance is " + this.getBalance());

            return false;
        }
    }
}

和主要 class

package com.company;

import org.omg.PortableServer.THREAD_POLICY_ID;


public class Main implements Runnable {
    Account account = new Account();
    public static void main(String[] args){
            Main main = new Main();
            for(int i= 0; i< 2; i++) {
                Thread c1 = new Thread(main, "customer" + i);
                c1.start();
            }
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "'s balance is " + account.getBalance());
        account.withdraw(60, Thread.currentThread().getName());
        //
    }
}

我在 getBalance() 中放置了 synchronized 关键字,以确保一次只能由一个线程访问它。但是我仍然得到负余额。

customer0's balance is 100.0
customer1's balance is 100.0
customer1 withdraw 60.0
Hello,  customer1 You current balance is 40.0
customer0 withdraw 60.0
Hello,  customer0 You current balance is -20.0

我做错了什么?

我认为你应该同步提取余额。

你刚才的代码可以让两个线程同时提现,但不能同时查询余额

你只需要一个个线程提现&一个个线程一次查询余额。

(感谢编辑建议)