Java 添加一个没有 Thread.sleep 的延迟和一个什么都不做的 while 循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20959805/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 05:33:55  来源:igfitidea点击:

Adding a delay without Thread.sleep and a while loop doing nothing

javamultithreadingdelaysleep

提问by user3166950

I need to add delay without using Thread.sleep() or a while loop doing nothing. The game im editing(Minecraft) clock runs on "Ticks" but they can fluctuate depending on your FPS.

我需要在不使用 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;
    }
}

The reason why i need a delay is because if i dont have one the code runs too fast and misses it and does not toggle.

我需要延迟的原因是因为如果我没有,代码运行太快而错过它并且不会切换。

采纳答案by clstrfsck

Something like the following should give you the delay you need without holding up the game thread:

类似下面的内容应该可以在不阻止游戏线程的情况下为您提供所需的延迟:

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

回答by Andrei Nicusan

long start = new Date().getTime();
while(new Date().getTime() - start < 1000L){}

is the simplest solution I can think about.

是我能想到的最简单的解决方案。

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

尽管如此,堆可能会被大量未引用的Date对象污染,这取决于您创建此类伪延迟的频率,可能会增加 GC 开销。

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.

归根结底,您必须知道,与Thread.sleep()解决方案相比,就处理器使用情况而言,这并不是更好的解决方案。