PhysicsThread.java啓動一個新線程。 run方法執行初始化方法。這種方法創建物理世界。之後,它開始一個while循環,以1000/60 = 16毫秒的間隔更新世界。然而,我在循環中得到了一個nullpointerexception
,因爲它並不總是知道世界,儘管我檢查了這一點。 可以解釋發生了什麼?線程執行順序的Java
PhysicsThread.java
public class PhysicsThread implements Runnable {
long fps = 60;
DiscreteDynamicsWorld dw;
long lasttime = System.currentTimeMillis();;
static int maxPhysicsObjects = 50000;
PhysicsThread() {
Thread t = new Thread(this);
t.setPriority(Thread.MIN_PRIORITY);
t.start();
}
@Override
public void run() {
System.out.println("Start thread");
init();
System.out.println("Start threadloop");
while(true) {
loop();
}
}
public void init() {
BroadphaseInterface broadphase = new AxisSweep3_32(new Vector3f(0,0,0), new Vector3f(200000,200000,200000), maxPhysicsObjects);//new DbvtBroadphase();
DefaultCollisionConfiguration collisionConfiguration = new DefaultCollisionConfiguration();
CollisionDispatcher dispatcher = new CollisionDispatcher(
collisionConfiguration);
SequentialImpulseConstraintSolver solver = new SequentialImpulseConstraintSolver();
dw = new DiscreteDynamicsWorld(dispatcher, broadphase,
solver, collisionConfiguration);
System.out.println("Made world");
dw.setGravity(new Vector3f(0, 0, -10));
}
public void loop() {
if (dw!=null) {
float delta = System.currentTimeMillis()-lasttime;
lasttime = System.currentTimeMillis();
dw.stepSimulation(delta/1000f, 1, 1/60f);
}
try {
Thread.sleep(1000/fps);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public DiscreteDynamicsWorld getWorld() {
return dw;
}
}
奇怪的是,''dw' get在調用'loop'方法之前被初始化。哪條生產線生產NPE?堆棧跟蹤的前幾行可能會有所幫助。 – 2012-03-07 12:37:39
你是否在說如果檢查'dw'是否爲空,你正在獲得NPE?這應該是不可能的,除非其他線程在此期間將'dw'改爲null,而我認爲這不會發生。 – Tudor 2012-03-07 12:43:03
除非'dw.stepSimulation()'在內部產生一個NPE,否則你不會顯示你的真實代碼,它不能在你的''loop''代碼中。 – stryba 2012-03-07 12:44:24