我正在制作简单的游戏,这是代码:
public class Game extends Canvas implements Runnable {
public void start() {
t = new Thread(this);
t.start();
}
@Override
public void run() {
setVisible(true); // visibility of the thread turn on
while (!t.isInterrupted()) {
if(condition for end the game) {
t.interrupt(); //here i need to destroy the thread
setVisible(false); //visibility to off
}
update();
render();
try {
Thread.sleep(20);
} catch(InterruptedException e) {}
}
}
}
我有另一个扩展 JFrame 的类,该类正在引入主菜单,如果我的“结束游戏的条件”为真,则线程消失并且菜单再次可见,这很好,但如果我想开始新的再次游戏,线程的行为很奇怪 - 似乎 Thread.sleep() 方法从 20 更改为 10,因为它的速度更快,可能我需要杀死线程,但我不知道如何,谢谢
最佳答案
简单,打破循环:
if(condition for end the game) {
t.interrupt(); //here i need to destroy the thread
setVisible(false); //visibility to off
break;
}
结束循环,线程就会结束。
关于java - 如何销毁一个线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20272075/