我正在做简单的游戏,这里是代码:如何销毁一个线程?
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,因为它的所有更快,也许我需要杀死线程,但我不知道怎么了,感谢
'break'不是一个好的选择,因为它只跳出当前循环。如果你有嵌套循环,你只会升一级,但不在线程之外。回报比较好。 – TwoThe