在没有Thread.sleep和while循环的情况下添加延迟

use*_*950 6 java multithreading sleep delay

我需要在不使用Thread.sleep()或while循环的情况下添加延迟.游戏即时编辑(Minecraft)时钟在"Ticks"上运行,但它们可能会根据您的FPS而波动.

public void onTick() {//Called every "Tick"
    if(variable){ //If my variable is true
            boolean = true; //Setting my boolean to true
            /**
            *Doing a bunch of things.
            **/
            //I need a delay for about one second here.
            boolean = false; //Setting my boolean to false;
    }
}
Run Code Online (Sandbox Code Playgroud)

我需要延迟的原因是因为如果我没有一个代码运行得太快而错过了它并且没有切换.

msa*_*ord 6

像下面这样的东西可以在不举起游戏线程的情况下为您提供所需的延迟:

private final long PERIOD = 1000L; // Adjust to suit timing
private long lastTime = System.currentTimeMillis() - PERIOD;

public void onTick() {//Called every "Tick"
    long thisTime = System.currentTimeMillis();

    if ((thisTime - lastTime) >= PERIOD) {
        lastTime = thisTime;

        if(variable) { //If my variable is true
            boolean = true; //Setting my boolean to true
            /**
            *Doing a bunch of things.
            **/
            //I need a delay for about one second here.
            boolean = false; //Setting my boolean to false;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


And*_*san 5

long start = new Date().getTime();
while(new Date().getTime() - start < 1000L){}
Run Code Online (Sandbox Code Playgroud)

is the simplest solution I can think about.

Still, the heap might get polluted with a lot of unreferenced Date objects, which, depending on how often you get to create such a pseudo-delay, might increase the GC overhead.

At the end of the day, you have to know that this is no better solution in terms of processor usage, compared to the Thread.sleep() solution.

  • 另外他在问题中说“没有while循环什么都不做”。 (4认同)