简体   繁体   中英

Java Basic Timing

Currently my project has no timing and is satisfactory but it would be a lot cleaner if I had timing. I would like to have it so after I declared whatever needs to be I can do something like:

if (timer == 2000) {
    System.out.println("2 seconds have passed since "timer" was declared!");
}

I haven't seen that much that went over this. Sorry if I'm missing something. I'm just looking for the best way to do this.

EDIT
I've been asked for more detail on why I need this so... btw this is for a zombie game

while(!Display.isCloseRequested()){
    if (whatever == 2 seconds){    //I obviously know a don't right the word seconds next the number 2
        for(int z = 0; z < 2; z++){
            SpawnaZombieAt(leftcorner,20,speed);
        }
     }
}

if I'm not clear enough I am trying to start some sort of timer. then for every 2 seconds or so 2 more zombies will spawn

Are you looking for System.currentTimeMillis() or System.nanoTime() ? The first is a low precision counter that corresponds to UTC, while the latter is a high precision timer that can be used to determine elapsed time.

If you want to launch a specific action after a specific delay, you can use a ScheduledExecutorService - for example:

ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.schedule(new Runnable() {
    public void run() {
        System.out.println("2 seconds have passed since this action was scheduled!");
    }
}, 2, TimeUnit.SECONDS);

And it will print your sentence after 2 seconds.

If you are after a stopwatch, the answers to this question propose several alternatives .

EDIT

Following your edit, the ScheduledExecutorService has a scheduleAtFixedRate method that would enable you to run a specific action every 2 seconds for example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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