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

时间:2014-01-06 21:41:52

标签: java multithreading delay sleep

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

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

3 个答案:

答案 0 :(得分: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;
        }
    }
}

答案 1 :(得分:4)

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

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

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

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

答案 2 :(得分:0)

一种方法是:

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)