这是我的代码
protected static Objects[] theObject;
private static Runnable objectDeployment = () -> {
MainThread.theObject = new Objects[noOfObjects];
for(int i=0; i<noOfObjects; i++) {
theObject[i] = new Objects();
theObject[i].setEnableMovement(true);
theObject[i].start();
}
};
private static RAMDS[] track;
private static Runnable scanner = () -> {
int no = noOfObjects;
track = new RAMDS[no];
for(int i=0; i<no; i++) {
int[] position = MainThread.theObject[i].getPosition();
int magnitude = MainThread.theObject[i].getMagnitude();
//check to see if there is an object within range
if(position[0] > 0 && position[0] < Wireframe.xlimit )
if(position[1] > 0 && position[1] < Wireframe.ylimit )
if(magnitude > 0) {
track[i] = new RAMDS();
track[i].objectId(i);
track[i].start();
}
}
};
public static void main(String[] args) {
// TODO Auto-generated method stub
noOfObjects = getNoOfObjects();
new Thread(objectDeployment).start();
new Thread(scanner).start();
}
}
因此,当线程 2 尝试访问本应由线程 1 创建的 object[i] 数组时,我收到空指针异常。我做错了什么?
这是我获取 noOfObjects 的方法
private static int getNoOfObjects() {
int deployedObjects = 0;
@SuppressWarnings("resource")
Scanner in = new Scanner(System.in);
System.out.print("How many objects should be deployed?");
deployedObjects =in.nextInt();
return deployedObjects;
}
最佳答案
您需要等待 objectDeployment 线程完成。你有一个竞争条件。当扫描器线程尝试使用对象[i]时,未分配它。
编辑: 将 objectDeployment 拆分为同步的 init 阶段,以及启动对象的 objectStart。顺便说一句,我认为对象的名称非常困惑。
protected static Objects[] theObject;
private static Runnable objectDeployment = () -> {
MainThread.theObject = new Objects[noOfObjects];
for(int i=0; i<noOfObjects; i++) {
theObject[i] = new Objects();
theObject[i].setEnableMovement(true);
}
};
private static Runnable objectStart = () -> {
for(int i=0; i<noOfObjects; i++) {
theObject[i].start();
}
};
private static RAMDS[] track;
private static Runnable scanner = () -> {
int no = noOfObjects;
track = new RAMDS[no];
for(int i=0; i<no; i++) {
int[] position = MainThread.theObject[i].getPosition();
int magnitude = MainThread.theObject[i].getMagnitude();
//check to see if there is an object within range
if(position[0] > 0 && position[0] < Wireframe.xlimit )
if(position[1] > 0 && position[1] < Wireframe.ylimit )
if(magnitude > 0) {
track[i] = new RAMDS();
track[i].objectId(i);
track[i].start();
}
}
};
public static void main(String[] args) {
// TODO Auto-generated method stub
noOfObjects = getNoOfObjects();
objectDeployment.run()
new Thread(objectStart).start();
new Thread(scanner).start();
}
}
关于java - 为什么线程创建的数组会返回空指针异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51849194/