我如何在 Java 中延迟?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24104313/
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-14 10:10:10  来源:igfitidea点击:

How do I make a delay in Java?

javawaitsleepthread-sleep

提问by ardb

I am trying to do something in Java and I need something to wait / delay for an amount of seconds in a while loop.

我正在尝试用 Java 做一些事情,我需要一些东西在 while 循环中等待/延迟几秒钟。

while (true) {
    if (i == 3) {
        i = 0;
    }

    ceva[i].setSelected(true);

    // I need to wait here

    ceva[i].setSelected(false);

    // I need to wait here

    i++;
}

I want to build a step sequencer and I'm new to Java. Any suggestions?

我想构建一个步进音序器,而且我是 Java 新手。有什么建议?

采纳答案by Boris the Spider

If you want to pause then use java.util.concurrent.TimeUnit:

如果要暂停,请使用java.util.concurrent.TimeUnit

TimeUnit.SECONDS.sleep(1);

To sleep for one second or

睡一秒钟或

TimeUnit.MINUTES.sleep(1);

To sleep for a minute.

睡一分钟。

As this is a loop, this presents an inherent problem - drift. Every time you run code and then sleep you will be drifting a little bit from running, say, every second. If this is an issue then don't use sleep.

由于这是一个循环,因此存在一个固有问题——漂移。每次你运行代码然后睡觉时,你都会从运行中漂移一点点,比如说,每一秒。如果这是一个问题,则不要使用sleep.

Further, sleepisn't very flexible when it comes to control.

此外,sleep在控制方面不是很灵活。

For running a task every second or at a one second delay I would stronglyrecommend a ScheduledExecutorServiceand either scheduleAtFixedRateor scheduleWithFixedDelay.

为了每秒或延迟一秒运行一项任务,我强烈建议使用 aScheduledExecutorServicescheduleAtFixedRateor 或scheduleWithFixedDelay

For example, to run the method myTaskevery second (Java 8):

例如,要myTask每秒运行该方法(Java 8):

public static void main(String[] args) {
    final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
    executorService.scheduleAtFixedRate(App::myTask, 0, 1, TimeUnit.SECONDS);
}

private static void myTask() {
    System.out.println("Running");
}

And in Java 7:

在 Java 7 中:

public static void main(String[] args) {
    final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
    executorService.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            myTask();
        }
    }, 0, 1, TimeUnit.SECONDS);
}

private static void myTask() {
    System.out.println("Running");
}

回答by Ruslan

You need to use the Thread.sleep()call.

你需要使用Thread.sleep()调用。

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

更多信息:http: //docs.oracle.com/javase/tutorial/essential/concurrency/sleep.html

回答by Anju Aravind

Use Thread.sleep(1000);

使用Thread.sleep(1000);

1000is the number of milliseconds that the program will pause.

1000是程序将暂停的毫秒数。

try
{
    Thread.sleep(1000);
}
catch(InterruptedException ex)
{
    Thread.currentThread().interrupt();
}

回答by Michael Gantman

Using TimeUnit.SECONDS.sleep(1);or Thread.sleep(1000);Is acceptable way to do it. In both cases you have to catch InterruptedExceptionwhich makes your code Bulky.There is an Open Source java library called MgntUtils (written by me) that provides utility that already deals with InterruptedExceptioninside. So your code would just include one line:

使用TimeUnit.SECONDS.sleep(1);orThread.sleep(1000);是可以接受的方式来做到这一点。在这两种情况下,您都必须抓住InterruptedException使您的代码变得笨重的地方。有一个名为 MgntUtils(由我编写)的开源 Java 库,它提供已经在InterruptedException内部处理的实用程序。所以你的代码只包含一行:

TimeUtils.sleepFor(1, TimeUnit.SECONDS);

See the javadoc here. You can access library from Maven Centralor from Github. The article explaining about the library could be found here

请参阅此处的 javadoc 。您可以从Maven CentralGithub访问库。可以在这里找到解释图书馆的文章

回答by Bachan Joseph

Use Thread.sleep(100);. The unit of time is milliseconds

使用 Thread.sleep(100);. 时间单位是毫秒

For example:

例如:

public class SleepMessages {
    public static void main(String args[])
        throws InterruptedException {
        String importantInfo[] = {
            "Mares eat oats",
            "Does eat oats",
            "Little lambs eat ivy",
            "A kid will eat ivy too"
        };

        for (int i = 0;
             i < importantInfo.length;
             i++) {
            //Pause for 4 seconds
            Thread.sleep(4000);
            //Print a message
            System.out.println(importantInfo[i]);
        }
    }
}

回答by dominic03

I know this is a very old post but this may help someone: You can create a method, so whenever you need to pause you can type pause(1000)or any other millisecond value:

我知道这是一篇很老的帖子,但这可能对某人有所帮助:您可以创建一个方法,因此无论何时需要暂停,您都可以输入pause(1000)或任何其他毫秒值:

public static void pause(int ms) {
    try {
        Thread.sleep(ms);
    } catch (InterruptedException e) {
        System.err.format("IOException: %s%n", e);
    }
}

This is inserted just above the public static void main(String[] args), inside the class. Then, to call on the method, type pause(ms)but replace mswith the number of milliseconds to pause. That way, you don't have to insert the entire try-catch statement whenever you want to pause.

它被插入到public static void main(String[] args), 的正上方。然后,要调用该方法,请键入pause(ms)但替换ms为要暂停的毫秒数。这样,您就不必在想要暂停时插入整个 try-catch 语句。

回答by Hecanet

use this:

用这个:

public static void wait(int ms){
        try
        {
            Thread.sleep(ms);
        }
        catch(InterruptedException ex)
        {
            Thread.currentThread().interrupt();
        }
    }

then you can call this method anywhere like:

那么你可以在任何地方调用这个方法,比如:

        wait(1000);