题目是:编写程序实现线程的同步.假设一个银行的ATM机,它可以允许用户存款也可以取款.现在一个账户上有200元,用户A和用户B都拥有在这个账户上存款和取款的权利.用户A将存入100元...
题目是:编写程序实现线程的同步.假设一个银行的ATM机,它可以允许用户存款也可以取款.现在一个账户上有200元,用户A和用户B都拥有在这个账户上存款和取款的权利.用户A将存入100元,而用户B将取出50元,那么最后账户的存款应该是250元。求代码
那位大哥大姐会做啊?我的是
//利用线程同步实现模拟银行取款和存款
class Account
{
private static int cunqian = 200;
String name;
static float amount;
static float bmount;
public Account(String name,float amount,float bmount)
{
this.name=name;
this.amount=amount;
this.bmount=bmount;
}
public synchronized static void deposit(float amt)
{
float tmp = amount;
tmp += amt;
try
{
Thread.sleep(10);//模拟其它处理所需要的时间,比如刷新数据库等
}
catch (InterruptedException e)
{
}
amount = tmp;
}
public synchronized static void withdraw(float bmt)
{
float tmp = bmount;
tmp -= bmt;
try
{
Thread.sleep(10);//模拟其它处理所需要的时间,比如刷新数据库等
}
catch (InterruptedException e)
{
}
bmount = tmp;
}
public static float getBalance()
{
return (amount+bmount);
}
}
class Customer extends Thread
{ public void run()
{
for(int i=0;i<=1;i++)
Account.deposit(100.0f);
Account.withdraw(50.0f);
}
}
public class AccountTest
{
public static void main(String[] args)
{
Customer customerA=new Customer();
Customer customerB=new Customer();
customerA.start();
customerB.start();
System.out.println();
System.out.println("最后总钱数:" + Account.getBalance());
}
}
运行结果为0,谁能帮我改正一下。
展开