我正在用JavaFX製作一個簡單的按鈕遊戲,我需要一個線程來運行,以便我可以檢查一個敵人或玩家是否還活着。我的問題不是開始和使用線程,而是在窗口關閉時停止它。在JavaFX中運行線程
我做了一個樣本類來演示我的意思。
private Thread thread;
private boolean running;
private Stage window;
public void run() {
while (running) {
System.out.println("Hello");
}
stopThread();
}
public synchronized void startThread() {
running = true;
thread = new Thread(this, "Monitor");
thread.start();
}
public synchronized void stopThread() {
running = false;
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void start(Stage stage) throws Exception {
window = new Stage();
window = stage;
Pane layout = new Pane();
Scene scene = new Scene(layout);
window.setOnCloseRequest(e -> {
e.consume();
close();
});
window.setScene(scene);
window.show();
}
public void close() {
window.close();
stopThread();
}
public static void main(String[] args) {
Things things = new Things();
things.startThread();
launch(args);
}
當我運行它,不斷地「你好」打印,但是當我嘗試關閉它,線程繼續運行和Eclispe的進入調試模式說:
Thread [JavaFX Application Thread] (Suspended (exception NullPointerException)) QuantumToolkit.runWithoutRenderLock(Supplier<T>) line: not available GlassWindowEventHandler.handleWindowEvent(Window, long, int) line: not available WinWindow(Window).handleWindowEvent(long, int) line: not available WinWindow(Window).notifyClose() line: not available WinApplication._runLoop(Runnable) line: not available [native method] WinApplication.lambda$null$145(Runnable) line: not available 2091156596.run() line: not available Thread.run() line: not available
我已經看過但是,在我的代碼周圍,找不到任何空的內容。
你退出應用程序時關閉該窗口,還是有其他的展示窗口? – 2015-03-30 23:31:11