简体   繁体   English

有没有一种方法可以在不使用睡眠的情况下增加Java程序的延迟?

[英]is there a way to add a delay to a java program without using sleep?

In my game i have some stats that i want to go down after a certain period of time but i cant use the sleep thing. 在我的游戏中,我有一些统计数据希望在一段时间后下降,但我无法使用睡眠功能。 Can someone give me an example of a better way of doing this? 有人可以给我一个更好的方法示例吗? I've seen videos on something called the swing timer but none of the videos are helping me much. 我看过有关“摇摆计时器”的视频,但是这些视频都帮不了我什么。 I've also heard about the timer util however there seems to be almost no videos on that. 我也听说过计时器实用程序,但是似乎几乎没有视频。

here's what I tried to do: 这是我尝试做的事情:

int hunger = 10;

 public void hungerDown(){
    try{
        Thread.sleep(5000);
        hunger--;
    }
    catch(Exception e){

    }
}

Are you trying to make a game? 您正在尝试制作游戏吗? If so you should have a gameloop. 如果是这样,您应该有一个游戏循环。 This will keep track of timing, updates, and rendering. 这将跟踪时间,更新和渲染。 Here is a good website to get you started. 这是一个很好的网站,可以帮助您入门。

http://gafferongames.com/game-physics/fix-your-timestep/ http://gafferongames.com/game-physics/fix-your-timestep/

ScheduledExecutorService execService = Executors.newSingleThreadScheduledExecutor();

public void hungerDown() {
    scheduledThreadPool.schedule(new Runnable() {
        hunger --;
    }, 5, TimeUnit.SECONDS);
}

Java has a mechanism TimerTask for this purpose. Java为此提供了一种TimerTask机制。 Eg, 例如,

long delayMs = 1000;
new Timer().schedule(
    new TimerTask() {
        @Override
        public void run() {
            /* your delayed logic */
        }
    },
    delayMs
);

Another option is to use ScheduledExecutorService and call ScheduledExecutorService.schedule(Callable<V> callable, long delay, TimeUnit unit) . 另一个选择是使用ScheduledExecutorService并调用ScheduledExecutorService.schedule(Callable<V> callable, long delay, TimeUnit unit) You can get an instance by using one the factory methods from java.util.concurrent.Executors . 您可以使用java.util.concurrent.Executors的工厂方法之一来获取实例。

Unable to offer a code example right now but you may find a DelayQueue useful. 目前无法提供代码示例,但您可能会发现DelayQueue有用。

Essentially - you could create a DelayQueue and post a delayed item into it. 本质上,您可以创建一个DelayQueue并将延迟的项目发布到其中。 Then fire up a Thread that just waits for something to come out of the queue. 然后启动一个Thread ,该Thread只等待队列中的内容出来。

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

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