繁体   English   中英

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

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

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

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

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

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;
        }
    }
}
long start = new Date().getTime();
while(new Date().getTime() - start < 1000L){}

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

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

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

其中一种方法是:

class Timer {
            private static final ScheduledExecutorService scheduledThreadPoolExecutor = Executors.newScheduledThreadPool(10);
    
            private static void doPause(int ms) {
                try {
                    scheduledThreadPoolExecutor.schedule(() -> {
                    }, ms, TimeUnit.MILLISECONDS).get();
                } catch (Exception e) {
                    throw new RuntimeException();
                }
            }
        }

然后你可以在你需要的地方使用Timer.doPause(50)

暂无
暂无

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

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