【问题标题】:Thread.sleep() in while loop doesn't work properly?while 循环中的 Thread.sleep() 不能正常工作?
【发布时间】:2026-01-31 11:40:01
【问题描述】:

对象应该每 5 秒改变一次模式(运动算法)。我第一次尝试使用 while 循环,但循环的迭代速度太快了。然后我添加了Thread.sleep(5000),但我的对象仍然只在一种算法中移动(scatterMode)。这是算法:

//LEVEL 1
//scatter for 7s 
//chase for 20s 
//scatter for 7s 
//chase for 20s 
//scatter for 5s 
//chase for 20s
//scatter for 5s 
//chase indefinite

这是代码。构造函数和变量声明在底部,如果需要查看的话。

public void updateMode() throws InterruptedException {  
    while(ghostalive){
        if(seconds<7){
            Thread.sleep(100);
            mode = scatterMode;
        }
        if(7<seconds && seconds<27){
            Thread.sleep(5000);
            mode = chaseMode;
        }
        if(27<seconds && seconds<34){
            Thread.sleep(5000);
            mode = scatterMode;
        }
        if(34<seconds && seconds<54) {
            Thread.sleep(5000);
            mode = chaseMode;
        }
        if(54<seconds && seconds>59) {
            mode = scatterMode;
        }
        if(59< seconds && seconds<79){
            mode = chaseMode;
        }
        if(seconds>84){
            mode = scatterMode;
            ghostalive=false;
        }
        seconds++;
        ghostalive=false;
    }
}

private int seconds=0;
private boolean ghostalive=true;

protected static final int chaseMode = 0;
protected static final int scatterMode = 1;

static int mode = scatterMode; //initially ghost start in scatterMode

public Ghost(int x, int y, Maze maze) throws InterruptedException{
    super(x, y, maze);
    futureDirection = 0;
    timer = 0;
    updateMode();
    //chaseMode = false; 
    //frightenedMode = false;
}     

public static int getMode(){
    return mode;
}

【问题讨论】:

  • 您只是将秒数增加 1,而您的睡眠时间从十分之一秒(100 毫秒)到 5 秒(5000 毫秒)不等。
  • 很抱歉,您的大部分代码没有多大意义,而且您尝试实现 Ghost 的方式也行不通。在编写游戏之前,您真的应该更多地研究 Java 基础知识。

标签: java multithreading while-loop sleep


【解决方案1】:

您的睡眠模式是毫秒和几秒的混合,但您希望计算秒数。

试试这样的:

while(ghostalive){

    if(seconds<7){
        mode = scatterMode;

    }

    if(7<seconds && seconds<27){
        mode = chaseMode;
    }

    if(27<seconds && seconds<34){
        mode = scatterMode;
    }

    if(34<seconds && seconds<54) {
        mode = chaseMode;
    }

    if(54<seconds && seconds>59) {
        mode = scatterMode;
    }

    if(59< seconds && seconds<79){
        mode = chaseMode;
    }

    if(seconds>84){
        mode = scatterMode;
        ghostalive=false;
    }

    seconds++;
    Thread.Sleep(1000);//Sleep for one second only

    //ghostalive=false; // Should this be here? Ghost is set to not alive after each loop?
}

我在 if 语句之后移动了 sleep ,以便在每个循环中保持一致。

【讨论】:

    【解决方案2】:

    当秒数正好是 7 或 34 或 54,...时,没有条件处理这些情况。它只是不输入任何 if 语句。

    【讨论】:

      【解决方案3】:

      不要从构造函数调用updateMode

      相反,开始一个新线程。

      到目前为止,可能会发生以下情况:您的 Ghost 正在创建,在构造函数完成之前经历了他的所有阶段。然后当你的主程序启动时,你的幽灵是ghostalive=false,并且已经在scatterMode

      为了调试,放入很多Loggin语句。最好使用日志记录 API,但许多初学者更喜欢 System.out.println。最好只打印您正在执行的操作 - 即您将重影设置为哪种模式。

      当您还添加游戏计时器时,您应该很容易看到幽灵首先经历了他的所有状态,甚至在您的实际游戏开始之前(即“游戏已开始”记录也是必须的。

      记录一点也不比打印困难。

      // for each class, add such a line:
      private static final LOG = java.util.logging.Logger.getLogger("packagename.classname");
      
      static {
        // Configure the active logging level manually
        // For larger projects, use a .properties file!
        LOG.setLevel(java.util.logging.Level.ALL);
      }
      
      // inside of appropriate methods, use
      if (LOG.isLoggable(Level.DEBUG)) {
        LOG.log(Level.DEBUG, "My ghost is now frightened.");
      }
      

      if 语句很重要。它可以通过热点很好地优化,因此如果禁用日志记录,则日志记录语句几乎是免费的。

      好处是您可以轻松打开和关闭这些语句。而System.out.println 您必须手动删除并读取到您的代码中。

      【讨论】:

        【解决方案4】:

        我认为您不应该依赖 Sleep 来测量时间,因为每次运行它时它的行为都会有所不同。线程可以休眠超过上述时间。睡眠仅将当前线程暂停特定时间。它不保证该线程将在同一时间后再次开始执行。

        【讨论】: