简体   繁体   English

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

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

I need to add delay without using Thread.sleep() or a while loop doing nothing.我需要在不使用 Thread.sleep() 或 while 循环的情况下添加延迟。 The game im editing(Minecraft) clock runs on "Ticks" but they can fluctuate depending on your FPS.游戏即时编辑(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.我需要延迟的原因是因为如果我没有,代码运行太快而错过它并且不会切换。

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;
        }
    }
}
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 Date objects, 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()解决方案相比,这在处理器使用方面并不是更好的解决方案。

One of approaches is :其中一种方法是:

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

and then you can use Timer.doPause(50) where you need.然后你可以在你需要的地方使用Timer.doPause(50)

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

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