我如何让 java 在执行下一行之前等待一秒钟,而不用 try/catch

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

How do i have java wait a second before executing the next line, without try/catch

javatry-catchwait

提问by mooL

I am wondering if there is a way to do this, without anything confusing or messy. also, when i do a wait()method, it has a java.lang.IllegalMonitorStateExceptionerror.

我想知道是否有办法做到这一点,没有任何混乱或混乱。另外,当我做一个wait()方法时,它有一个java.lang.IllegalMonitorStateException错误。

回答by Andrew Li

The Thread.sleep()method can do what you want. It's a simple approach that stops execution for a given amount of time (not always accurate). Per the Oracle docs:

Thread.sleep()方法可以做你想做的。这是一种简单的方法,可以在给定的时间内停止执行(并不总是准确的)。根据Oracle 文档

Thread.sleep causes the current thread to suspend execution for a specified period. This is an efficient means of making processor time available to the other threads of an application or other applications that might be running on a computer system.

Thread.sleep 使当前线程暂停执行一段指定的时间。这是使处理器时间可用于应用程序的其他线程或可能在计算机系统上运行的其他应用程序的有效方法。

So, to call it, use,

所以,调用它,使用,

Thread.sleep(1000);

This will sleep for one second until further execution. The time is in milliseconds or nanoseconds.

这将休眠一秒钟,直到进一步执行。时间以毫秒或纳秒为单位。

This method may not always be accurate due to the OS and its configuration.

由于操作系统及其配置,此方法可能并不总是准确的。

回答by Moonlit

Once again, Guavais your friend:

再一次,番石榴是你的朋友:

Uninterruptibles.sleepUninterruptibly(1,TimeUnit.SECONDS);

and this is how it is implemented:

这是它的实现方式:

 public static void sleepUninterruptibly(long sleepFor, TimeUnit unit) {
    boolean interrupted = false;
    try {
      long remainingNanos = unit.toNanos(sleepFor);
      long end = System.nanoTime() + remainingNanos;
      while (true) {
        try {
          // TimeUnit.sleep() treats negative timeouts just like zero.
          NANOSECONDS.sleep(remainingNanos);
          return;
        } catch (InterruptedException e) {
          interrupted = true;
          remainingNanos = end - System.nanoTime();
        }
      }
    } finally {
      if (interrupted) {
        Thread.currentThread().interrupt();
      }
    }
  }

br

br

回答by M Imam Pratama

Without Thread and try/catch:

没有 Thread 和 try/catch:

static void pause(){
    long Time0 = System.currentTimeMillis();
    long Time1;
    long runTime = 0;
    while (runTime < 1000) { // 1000 milliseconds or 1 second
        Time1 = System.currentTimeMillis();
        runTime = Time1 - Time0;
    }
}

Update:

更新:

awilkinsonis right, the above method is a really bad hack. By the way, if you just want a ready to use method to wait for a second or more, even if it uses try/catch, then I would recommend this:

awilkinson是对的,上述方法是一个非常糟糕的黑客。顺便说一句,如果你只是想要一个随时可用的方法等待一秒钟或更长时间,即使它使用 try/catch,那么我会推荐这个:

public static void pause(double seconds)
{
    try {
        Thread.sleep((long) (seconds * 1000));
    } catch (InterruptedException e) {}
}

回答by Saravana

In Java

在 Java 中

Thread.sleep(intervalInMills);
TimeUnit.MILLISECONDS.sleep(intervalInMills);

Timer

定时器

new Timer().scheduleAtFixedRate(task, delay, period);

With Executor Framework

使用 Executor 框架

ScheduledExecutorService.scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit)

With Spring,

与春天,

@Scheduled(fixedDelay = 1000)
private void method() {
    // some code
}

You can also schedule cronor fixedRatewith initialDelay.

您还可以安排cronfixedRateinitialDelay