写了一个小程序,我觉应该是同步的,但结果不正确。程序是模拟银行账户的流水
public class Account {
private int money = 60000;
public int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
}
public class Save implements Runnable{
private Account account;
public Save(Account account) {
this.account=account;
}
@Override
public void run() {
for(int i=0;i<50000;i++){
synchronized (account) { //连续执行一定放入同步快中
account.setMoney(account.getMoney()+1);
// System.out.println("向账户存了1元,账户余额"+account.getMoney()+"元");
}
}
}
}
public class Take implements Runnable{
private Account account;
public Take(Account account) {
this.account=account;
}
@Override
public void run() {
for(int i=0;i<50000;i++){
synchronized (account) {
if(account.getMoney() > 0){
account.setMoney(account.getMoney()-1);
// System.out.println("向账户取了1元,账户余额"+account.getMoney()+"元");
}else{
// System.out.println("账户余额不足");
}
}
}
}
}
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Account account = new Account();
Save save = new Save(account);
Take take = new Take(account);
Thread thread1 = new Thread(save);
Thread thread2 = new Thread(take);
System.out.println("账户余额为"+account.getMoney());
System.out.println("开始");
thread1.start();
thread2.start();
System.out.println("最后账户余额为:"+account.getMoney());
}
}
存钱和取钱的钱数是一样的,所以总数应该还是60000,但结果不是这个数。是不是我Main线程先运行结束了?所以显示出来的“最后账户余额”不正确。
撒科打诨
慕妹3242003
郎朗坤
慕尼黑的夜晚无繁华
相关分类