Java多线程在修改同一个变量的问题

请问以下的程序的做的事情是:两个线程,都针对bank对象的money字段作减法操作,但打印结果为什么是
left money 200
left money 200
或者是
left money -600
left money -600

public class Test1 {
    public static void main(String[] args) {
        Bank bank = new Bank();
        Thread thread1 = new MoneyThread(bank);
        Thread thread2 = new MoneyThread(bank);
        thread1.start();
        thread2.start();
    }
}

class Bank {
    private int money = 1000;
    public int getMoney(int number) {
        if (number < 0 ||number > money) {
            return -1;
        } else {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            money -= number;
            System.out.println("left money " + money);
            return number;
        }
    }   
}

class MoneyThread extends Thread {
    private Bank bank;
    public MoneyThread(Bank bank) {
        this.bank = bank;
    }
    @Override
    public void run() {
        bank.getMoney(800);
    }
}
阅读 8.1k
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进