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