有个Bank类, 属性money=0;然后创建三个线程,调用addmoney()往bank里面加钱,
我这样写,为什么不能同步呢 ? 结果不是300万呀?新手请指教.
public class Bank {
private int money=0;
public int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
public void addMoney(int money){
this.money+=money;
}
public void subMoney(int money){
this.money-=money;
}
}
public class test2 implements Runnable {
private Bank bank;
public test2(Bank bank) {
this.bank = bank;
}
@Override
public synchronized void run() {
for (int i = 0; i < 1000; i++) {
bank.addMoney(1000);
}
}
public static void main(String[] args) {
Bank bank = new Bank();
test2 r1 = new test2(bank);
test2 r2 = new test2(bank);
test2 r3 = new test2(bank);
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
Thread t3 = new Thread(r3);
t1.start();
t2.start();
t3.start();
System.out.println(bank.getMoney());
}
}