我正在尝试制作一款 Android 游戏,并且我正在关注一些代码示例以使我的游戏循环正常工作。它涉及制作一个新线程。在该run()
方法中,我有一个 try/finally 块。在 finally 块执行后NullPointerException
会抛出一个。我不知道为什么,似乎没有什么是空的,即使是空的,也没有什么引用任何空的。我以为可能this
是空的,但似乎不是。这是我认为相关的代码:
public class MainThread extends Thread {
private boolean running;
private final SurfaceHolder holder;
private boolean GameIsRunning = false;
private int mMode;
public static final int STATE_LOSE = 1;
public static final int STATE_PAUSE = 2;
public static final int STATE_READY = 3;
public static final int STATE_RUNNING = 4;
public static final int STATE_WIN = 5;
private MainGame game;
public MainThread(SurfaceHolder holder, MainGamePanel panel) {
super();
this.holder = holder;
game = new MainGame(panel.getContext());
mMode = STATE_RUNNING;
}
@Override
public void run() {
while (running) {
Canvas c = null;
try {
c = holder.lockCanvas(null);
synchronized (holder) {
if (mMode == STATE_RUNNING) {
updateAll();
}
drawAll(c);
}
} finally {
// do this in a finally so that if an exception is thrown
// during the above, we don't leave the Surface in an
// inconsistent state
if (c != null) {
holder.unlockCanvasAndPost(c);
}
} // <<<<<<<<<<<<< After this line executes a null pointer exception is thrown
}
}
线程的创建:
public class MainGamePanel extends SurfaceView implements SurfaceHolder.Callback{
private MainThread thread;
public MainGamePanel(Context context) {
super(context);
getHolder().addCallback(this);
// create the game loop thread
thread = new MainThread(getHolder(), this);
setFocusable(true);
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
thread.setRunning(true);
thread.start();
}
谢谢!