在没有Thread.sleep和while循环的情况下添加延迟 [英] Adding a delay without Thread.sleep and a while loop doing nothing

查看:297
本文介绍了在没有Thread.sleep和while循环的情况下添加延迟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

这篇关于在没有Thread.sleep和while循环的情况下添加延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆