我如何在 Java 中延迟? [英] How do I make a delay in Java?

查看:39
本文介绍了我如何在 Java 中延迟?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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++;
}

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

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

推荐答案

如果你想暂停然后使用 java.util.concurrent.TimeUnit:

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

TimeUnit.SECONDS.sleep(1);

睡一秒钟或

TimeUnit.MINUTES.sleep(1);

睡一分钟.

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

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, sleep isn't very flexible when it comes to control.

为了每秒或延迟一秒运行一项任务,我强烈推荐ScheduledExecutorServicescheduleAtFixedRatescheduleWithFixedDelay.

For running a task every second or at a one second delay I would strongly recommend a ScheduledExecutorService and either scheduleAtFixedRate or scheduleWithFixedDelay.

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

For example, to run the method myTask every second (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");
}

在 Java 7 中:

And in 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");
}

这篇关于我如何在 Java 中延迟?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆