经过一定时间后用 Java 打印一些东西

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18478677/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 01:59:42  来源:igfitidea点击:

Printing something in Java after a certain amount of time has passed

javatimer

提问by 23k

I'm working on a text adventure game for my Java class, and I'm running into a problem while trying to time a print statement from showing up in the console.

我正在为我的 Java 课程开发文本冒险游戏,并且在尝试对打印语句显示在控制台中的时间进行计时时遇到了问题。

Basically after 45 seconds I would like a print statement to show up, in this case the print statement would be reminding the user that they need to let their virtual dog out...

基本上在 45 秒后,我希望显示一个打印语句,在这种情况下,打印语句将提醒用户他们需要让他们的虚拟狗出去......

I also need the timer to reset after the user gives the correct command.

我还需要在用户给出正确命令后重置计时器。

采纳答案by ash

import java.util.Timer;
import java.util.TimerTask;

...

Timer timer = new Timer();
timer.schedule(new TimerTask() { 
   @Override  
   public void run() {
       System.out.println("delayed hello world");
   }
},  45000);

Timer

计时器

TimerTask

定时器任务

To cancel the timer, either use a TimerTask variable to remember the task and then call its cancel() method, or use timer.purge(); the latter cancels all tasks on the timer. To schedule the task again, just repeat.

要取消计时器,请使用 TimerTask 变量来记住任务,然后调用其 cancel() 方法,或者使用timer.purge(); 后者取消计时器上的所有任务。要再次安排任务,只需重复即可。

You'll probably want to do more advanced operations in the future, so reading the Timer API docs is a good idea.

您将来可能希望进行更高级的操作,因此阅读 Timer API 文档是个好主意。

回答by ozborn

Just tell the thread to sleep for 45 seconds, there is a tutorial here:

只需告诉线程休眠 45 秒,这里有一个教程:

http://docs.oracle.com/javase/tutorial/essential/concurrency/sleep.html

http://docs.oracle.com/javase/tutorial/essential/concurrency/sleep.html

回答by 0decimal0

 Timer timer = new Timer();
 timer.schedule(new TimerTask(){
    public void run() {
       System.out.println(" let the virtual dog out ");
    }
  }, 45000);

回答by Ali

Tell the main thread to sleep might not be ideal as it will cause your program to basically stop. Use a another thread(need to do a little multi-threading) for timing your output and do a check if the message should be printed after the 45s.

告诉主线程休眠可能并不理想,因为它会导致您的程序基本上停止。使用另一个线程(需要做一点多线程)来计时输出并检查是否应该在 45 秒后打印消息。

回答by Sri Harsha Chilakapati

Try running in a new Thread.

尝试在新线程中运行。

new Thread(new Runnable()
{
    public void run()
    {
        Thread.sleep(45000);
        System.out.println("My message");
    }
})
.run();

This should work.

这应该有效。