首页 文章

Android - 暂停和恢复线程使我的线程变慢

提问于
浏览
0

我在画布中创建一个示例游戏到表面视图 .

我正在使用更新和绘制方法,所有工作 . 现在我想暂停并恢复比赛 . 我在互联网上找到的方法很有效,但是当游戏恢复时它会慢得多 .

我的循环游戏:

while(playing){  // on runnable thread
       update(); // update all objects of the game
       draw();  //  draw all objects of the game
       control();  // first remove dead objects, after sleep the Thread.
    }

我的暂停和恢复方法:

public void pause(){
        playing = false;
        try{
            gameThead.sleep(17);
        } catch(ex){};
    }

    public void resume(){
        playing = true;
        gameThread = new gameThread(this); // this object is a runnable
        gameThread.start();
    }

有谁知道为什么放慢速度?和解决方案? (注意:我试图给出一个固定的睡眠而不是一个变量,结果是同样的慢)

谢谢 .

@EDIT

我发现了麻烦 .

我的活动有一个监听器onResume(),这启动了线程初始化...但是在我的surfaceview构造中我也做了......恢复:当游戏开始时,有2个线程......暂停不做游戏太慢,暂停做游戏是在正确的速度...开始游戏做游戏有2个线程(和2个更新)

谢谢 .

1 回答

  • 1

    如果 playing 为false,则不需要 sleep 线程,你可以这样做:

    // my thread
    while(playing && !paused){  // on runnable thread
       update(); // update all objects of the game
       draw();  //  draw all objects of the game
       control();  // first remove dead objects, after sleep the Thread.
    }
    
    public void pause(){
        paused = true;
    }
    
    public void resume(){
        paused = false;
    }
    
    public void quit() {
        playing = false;
    }
    

    我认为你原来的问题是这段代码:

    gameThread = new gameThread(this); // this object is a runnable
        gameThread.start();
    

    每当你“恢复”你正在创造一个新线程的游戏时,如果你期望它暂停很多(从睡眠的长度来判断),这可能是一个记忆密集的习惯 . 尝试保持1个单线程并切换标志 .

相关问题