【发布时间】:2026-02-09 05:10:02
【问题描述】:
我正在尝试制作一款 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();
}
谢谢!
【问题讨论】:
-
堆栈跟踪会告诉你——这就是它的用途。至少把它贴在这里,让我们看看。
-
this不能永远是null。这是不可能的。
标签: java android nullpointerexception try-finally