2013-11-28 61 views
1

我正在做简单的游戏,这里是代码:如何销毁一个线程?

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,因为它的所有更快,也许我需要杀死线程,但我不知道怎么了,感谢

回答

2

简单,打破循环:

if(condition for end the game) { 
     t.interrupt(); //here i need to destroy the thread 
     setVisible(false); //visibility to off 
     break; 
    } 

您结束循环并且线程将结束。

+4

'break'不是一个好的选择,因为它只跳出当前循环。如果你有嵌套循环,你只会升一级,但不在线程之外。回报比较好。 – TwoThe

0

终止线程的最简单方法是退出运行功能。没有特殊的处理要求,一个简单的return伎俩。

对你有兴趣,你可能要考虑使用ScheduledExecutorService,它允许你安排一个Runnable以固定的速度运行:

executor.scheduleAtFixedRate(gameLoop, 0, 1000/TARGET_FPS, TimeUnit.MILLISECONDS); 

请记住,你再需要拿出实际的循环您gameLoop的,因为这是由固定利率通话,将其降低到完成:

public void run() { 
    if (pause == false) { 
    update(); 
    render(); 
    } 
} 

pause是一个布尔值,你应该出于某种原因想要把渲染上暂停了一段时间。

通过此设置,您可以简单地通过调用executor.shutdown()来终止游戏,然后再禁止任何对runnable的进一步调用。

0

没有真正的话题,但我做了一个小游戏,和起搏我使用的定时器(从swingx):

public class MainGameLoop implements ActionListener{ 
    Timer timer; 
    public static void main(...){ 
      timer = new Timer(10, this); 
     timer.start(); 
    } 

    public void actionPerformed(ActionEvent e) { 
     ... 
    } 
} 

工作以及给我。