简体   繁体   English

while循环中的Thread.sleep()无法正常工作吗?

[英]Thread.sleep() in while loop doesn't work properly?

The object is supposed to change modes (movement algorithm) every 5 seconds. 该对象应该每5秒更改一次模式(运动算法)。 I first tried with a while loop but the loop was iterating way too fast. 我首先尝试了一个while循环,但是循环太快了。 Then I added Thread.sleep(5000) but still my object moves only in one algorithm ( scatterMode ). 然后,我添加了Thread.sleep(5000)但是我的对象仍然只能以一种算法( scatterMode )移动。 Here is the algorithm: 这是算法:

//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

And here is the code. 这是代码。 The constructor and variable declarations are at the bottom if you need to see them. 如果需要查看构造函数和变量声明,请在底部。

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;
}

Your sleep pattern is mixture of milliseconds and several seconds, but you are expecting to count seconds. 您的睡眠方式是毫秒和几秒钟的混合,但是您希望数秒。

Try something like this: 尝试这样的事情:

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?
}

I have moved the sleep after the if statements so that it is consistent in each loop. 我将睡眠移动到了if语句之后,以便在每个循环中保持一致。

I think you should not rely on Sleep for measuring time because it can behave differently everytime you run it. 我认为您不应该依赖睡眠来测量时间,因为它在每次运行时都会有所不同。 Thread can goto sleep for more than the mentioned time. 线程可以进入睡眠时间超过上述时间。 Sleep only pauses current thread for specific time. 睡眠仅在特定时间暂停当前线程。 It does not guarantees that this thread will start executing again after same time. 它不能保证此线程将在同一时间之后再次开始执行。

Do NOT invoke updateMode from the constructor. 不要调用updateMode从构造函数。

Instead, start a new thread. 而是,启动一个新线程。

As of now, probably the following happens: your Ghost is creates, goes through all of his stages before the constructor is complete. 到目前为止,可能发生以下情况:您的Ghost已创建,在构造函数完成之前经历了他的所有阶段。 Then when your main program starts, your ghost is ghostalive=false and in scatterMode already. 然后,当您的主程序启动时,您的幽灵为ghostalive=falsescatterMode已经处于scatterMode

For debugging, put in a lot of Loggin statements. 为了进行调试,请放入许多Loggin语句。 It's best to use the logging APIs, but many beginners prefer System.out.println . 最好使用日志记录API,但是许多初学者更喜欢System.out.println It is a good practise to just print what you are doing - ie which mode you set the ghost to. 只是打印您正在做的事情是个好习惯,即您将幻像设置为哪种模式。

When you then also add game timer things, you should easily see that the ghost first goes through all of his states, before your actual game even started (ie a "game has started" logging is also a must. 然后,当您还添加游戏计时器内容时,您应该很容易地看到,在您的实际游戏开始之前,幽灵首先经历了他的所有状态(即,“游戏已经开始”记录也是必须的)。

Logging is not at all more difficult than printing. 记录根本没有打印困难。

// 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.");
}

The if statement is important. if语句很重要。 It can be optimized well by hotspot, so that if logging is disabled, the logging statements come at next to no cost. 可以通过热点很好地对其进行优化,因此,如果禁用了日志记录,则日志记录语句几乎是免费的。

The good thing is that you can turn on and off these statements easily. 好消息是您可以轻松地打开和关闭这些语句。 While System.out.println you have to manually remove and readd to your code. System.out.println您必须手动删除并读取代码。

When seconds is exactly 7 or 34 or 54,..., there is no condition to handle these cases. 当秒数恰好是7或34或54 ...时,没有条件可以处理这些情况。 It just doesn't enter in any of the if statements. 它只是不输入任何if语句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM