在标准Java中,此代码可以正常工作。但我认为不应该。
class Data{
private String name;
public String getName(){
return name;
}
public void setName(String name){
this.name=name;
}
}
class Test{
private Data mData;
public void back(){
mData=new Data();
mData.setName("You");
}
public void go(){
Thread mThread = new Thread(){
public void run(){
System.out.println(mData.getName());
}
};
mThread.start();
}
}
但是,当在Android中执行类似操作时,它将引发NullPointerException。
private void writeApp(){
Thread mThread = new Thread(){
public void run(){
Log.d(TAG,modelData.getAppName());
}
};
mThread.start();
}
//编辑
public void appOpens(String appPackageName) throws NameNotFoundException{
modelData = new ModelData();
modelData.setOpen(true);
modelData.setAppPackageName(appPackageName);
modelData.setOpenTime(getTimeMil());
setAppNameAndAppVersion();
}
private void writeApp(){
Log.d(TAG+1,modelData.getAppName());//works fine
Thread mThread = new Thread(){
public void run(){
Log.d(TAG+2,modelData.getAppName());//doenst works throws NullPointerException
}
};
mThread.start();
}
appOpens(String appPackageName)
拳头。Log.d(TAG+1,modelData.getAppName())
不会抛出NullPointerException,但是Log.d(TAG+2,modelData.getAppName())
抛出我认为这是正确的行为,因为我不共享实例到线程。只能从主线程访问它。但是在标准java中,第二个线程访问了我的主线程,怎么会这样? 最佳答案
您可以将modelData分配给最终的本地字段吗?
private void writeApp(){
final ModelData data = modelData;
Log.d(TAG+1,data.getAppName());//works fine
Thread mThread = new Thread(){
public void run(){
Log.d(TAG+2,data.getAppName());//doenst works throws NullPointerException
}
};
mThread.start();
}
如果
//works fine
仍然起作用,则//doesnt work
现在将起作用。