温馨提示×

Java settimeout怎样调整精度

小樊
85
2024-06-25 17:46:34
栏目: 编程语言
Java开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在Java中,没有直接的setTimeout方法来实现延迟执行代码的功能。但是可以使用ScheduledExecutorService类来实现类似的功能,并且可以调整延迟执行的精度。

下面是使用ScheduledExecutorService实现延迟执行的示例代码:

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class DelayedExecution {

    public static void main(String[] args) {
        ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);

        executor.schedule(() -> {
            System.out.println("Delayed task executed");
        }, 1000, TimeUnit.MILLISECONDS); // 设置延迟执行时间为1秒

        executor.shutdown();
    }
}

在这个示例中,ScheduledExecutorService会在1秒后执行传入的任务。你可以通过调整TimeUnit.MILLISECONDS的参数来调整执行的精度,例如设置为TimeUnit.SECONDS则表示以秒为单位的延迟执行。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:java settimeout 如何处理时间精度

0