请问多线程异常问题

denny009 2006-02-11 02:45:33
import java.util.*;
import java.text.*;

public class AccountManager{
protected CustomerAccount savings;
protected CustomerAccount checking;
public final static int SAVINGS_ACCOUNT=1;
public final static int CHECKING_ACCOUNT=2;
public static void main(String args[])
{
int transfers=1000000;

AccountManager am=new AccountManager(transfers);


}
public AccountManager(int transfers){
savings=new CustomerAccount(SAVINGS_ACCOUNT,1000);
savings=new CustomerAccount(CHECKING_ACCOUNT,1000);
NumberFormat formatter=NumberFormat.getCurrencyInstance(Locale.US);
System.out.println("Total balance before transfers: "+
formatter.format(savings.getbalance()+checking.getbalance()));
transfersManager tm1=new transfersManager(checking,savings,transfers);
transfersManager tm2=new transfersManager(savings,checking,transfers);
Thread t1=new Thread(tm1);
Thread t2=new Thread(tm2);
t1.start();
t2.start();
try{
t1.join();
t2.join();
}catch(Exception e){

};
System.out.println("Total balance after transfers: "+
formatter.format(savings.getbalance()+checking.getbalance()));
}
class transfersManager implements Runnable{
public CustomerAccount fromaccount;
public CustomerAccount toaccount;
protected int transferscount;
public transfersManager(CustomerAccount fromacct,CustomerAccount toacct,int transfers){
fromaccount=fromacct;
toaccount=toacct;
transferscount=transfers;
}

public void run()
{
double balance;
double transfersamount;
for(int i=0;i<transferscount;i++){
synchronized (fromaccount){

balance=fromaccount.getbalance();
transfersamount=(int)balance*Math.random();
balance=balance-transfersamount;
fromaccount.setbalance(balance);
synchronized (toaccount){
balance=toaccount.getbalance();
balance+=transfersamount;
toaccount.setbalance(balance);
}
}
}
}}
class CustomerAccount{
protected int accounttype;
protected double balance;
public CustomerAccount(int type,double bal){
accounttype=type;
balance=bal;
}
public int getaccounttype(){
return accounttype;
}
public double getbalance(){
return balance;
}
public void setbalance(double newbal){
balance=newbal;
}
}
}
这是书上的举例,我运行后为什么出现异常?
Exception in thread "main" java.lang.NullPointerException
at AccountManager.<init>(AccountManager.java:21)
at AccountManager.main(AccountManager.java:13)
Press any key to continue...
...全文
82 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
leonard_sun 2006-02-12
  • 打赏
  • 举报
回复
ding
congliu 2006-02-11
  • 打赏
  • 举报
回复
用synchronized关键字把引起race condition的code分开
或者使用wait和notify进行同步

62,626

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧