2016-04-03 30 views
0

我一直在制作mario游戏并取得了不错的进展。现在我需要在世界之间切换。首先,我停止运行更新并绘制方法的线程,然后删除世界上的所有东西(玩家,敌人,草地等),然后加载一个新的世界。然后我尝试再次启动线程。但是由于某种原因,在停止线程之后,没有任何事情会在那之后执行,并且就在那里“冻结”。Thread.join()之后无法执行任何操作

private synchronized void clearWorld() { 
    stop(); 
    System.out.println("Stopped"); 
    for(int a = 0 ; a < handler.wall.size() ; a++) handler.wall.remove(handler.wall.get(a)); 
    for(int b = 0 ; b < handler.creature.size() ; b++) handler.creature.remove(handler.creature.get(b)); 
    System.out.println("Everything removed"); 
} 

private synchronized void switchWorld(String path) { 
    world = new World(this , path); 
    start(); 
    System.out.println("Thread started"); 
} 
public synchronized void stop() { 
    if(!running) return ; 
    running = false ; 
    try { 
     Main.getGame().thread.join(); 
    } catch (InterruptedException e) { 
     e.printStackTrace(); 
    } 
} 
public synchronized void start() { 
    if(running) return ; 
    running = true ; 
    Main.game.thread.start(); 
} 

public void run() { 
    init(); 
    long lastTime = System.nanoTime(); 
    final double amountOfTicks = 60.0; 
    double ns = 1000000000/amountOfTicks; 
    double delta = 0; 
    int updates = 0; 
    int frames = 0; 
    long timer = System.currentTimeMillis(); 

    while(running){ 
     long now = System.nanoTime(); 
     delta += (now - lastTime)/ns; 
     lastTime = now; 
     if(delta >= 1){ 
      tick(); 
      updates++; 
      delta--; 
     } 
     render(); 
     frames++; 

     if(System.currentTimeMillis() - timer > 1000){ 
      if(world.Goombas==getPlayer().gKilled) { 
       clearWorld(); 
       switchWorld("/pipe_world1.txt"); 
      } 
      timer += 1000; 
      System.out.println(updates + " Ticks, Fps " + frames); 
      updates = 0; 
      frames = 0; 
     } 

    } 
} 
+0

也许这有助于。 “一旦一个线程停止你不能重新启动它”http://stackoverflow.com/questions/1881714/how-to-start-stop-restart-a-thread-in-java – RubioRic

+0

但它甚至不打印停止!看看clearWorld方法 –

+0

我怀疑你有死锁的情况。你能否向我们展示一个堆栈转储,并在发生这种情况时查看线程在调试器中执行的操作? –

回答

1

Thread.join挂起调用线程并等待目标线程死掉。代码中发生的事情是,调用clearWorld的线程正在等待游戏线程终止。

编辑:更新后,我看到它是游戏线程本身调用join。这将保证导致join的呼叫永远被阻止。有关说明,请参阅Thread join on itself

由于您在一个线程中做了所有事情,因此完全不需要joinstart

如果你确实有多个线程,那么更好的方法是在你的游戏线程中有一个变量来检查游戏执行是否暂停。也许是这样的:那么

class GameThread extends Thread { 
    private volatile boolean paused; 

    public void run() { 
     while (true) { 
      if (!paused) { 
       executeGameLogic(); 
      } else { 
       // Put something in here so you're not in a tight loop 
       // Thread.sleep(1000) would work, but in reality you want 
       // to use wait and notify to make this efficient 
      } 
     } 
    } 

    public void pause() { 
     paused = true; 
    } 

    public void unpause() { 
     paused = false; 
    } 
} 

clearWorldswitchWorld方法可以调用pauseunpause游戏线程上。

相关问题