迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > Java >

如何在 Java 中延迟几秒钟的时间

作者:迹忆客 最近更新:2023/12/17 浏览次数:

本教程介绍了如何在 Java 中制造程序延时,并列举了一些示例代码来了解它。

制造延时有几种方法,比如 TimeUnit.sleep()ScheduleAtFixedRate()Thread.sleep() 等方法。我们来看看例子。


在 Java 中使用 Thread.sleep() 方法制造延迟

Thread 是一个 Java 类,用于创建和并发执行任务,并提供了一个 sleep() 方法来暂停当前执行一段时间。

public class SimpleTesting {
  public static void main(String[] args) {
    try {
      for (int i = 0; i < 2; i++) {
        Thread.sleep(1000);
        System.out.println("Sleep " + i);
      }
    } catch (Exception e) {
      System.out.println(e);
    }
  }
}

输出:

Sleep 0
Sleep 1

在 Java 中使用 TimeUnit.sleep() 方法进行延迟

在这个例子中,我们使用了 TimeUnit 类的 sleep() 方法,用来对指定的时间进行执行延迟。TimeUnit 类属于 Java 中的一个并发 API 包。

import java.util.concurrent.TimeUnit;

public class SimpleTesting {
  public static void main(String[] args) {
    try {
      for (int i = 0; i < 2; i++) {
        TimeUnit.SECONDS.sleep(2);
        System.out.println("Sleep " + i);
      }
    } catch (Exception e) {
      System.out.println(e);
    }
  }
}

输出:

Sleep 0
Sleep 1

在 Java 中使用 ScheduledExecutorService 进行延迟

Java 提供了一个类 ScheduledExecutorService 来调度并发环境下的执行。我们可以使用它里面的 run() 方法来执行单独的执行路径。请看下面的例子。

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

public class Main {
  public static void main(String args[]) {
    try {
      final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
      executorService.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
          executeTask();
        }
      }, 0, 1, TimeUnit.SECONDS);
    } catch (Exception e) {
      System.out.println(e);
    }
  }
  private static void executeTask() {
    System.out.println("Task Executing... ");
  }
}

输出:

Task Executing... 
Task Executing... 
Task Executing... 

在 Java 中使用 ScheduledExecutorService 进行延迟

如果你使用的是 Java 9 或更高版本,你可以使用方法引用的概念,在 scheduleAtFixedRate() 方法内部调用方法。请看下面的例子。

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

public class SimpleTesting {
  public static void main(String[] args) {
    try {
      final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
      executorService.scheduleAtFixedRate(SimpleTesting::executeTask, 1, 2, TimeUnit.SECONDS);
    } catch (Exception e) {
      System.out.println(e);
    }
  }
  private static void executeTask() {
    System.out.println("Task Executing... ");
  }
}

输出:

Task Executing... 
Task Executing... 
Task Executing... 

上一篇:如何在 Java 中把 Hashmap 转换为 JSON 对象

下一篇:没有了

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Do you understand JavaScript closures?

发布时间:2025/02/21 浏览次数:108 分类:JavaScript

The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.

Do you know about the hidden traps in variables in JavaScript?

发布时间:2025/02/21 浏览次数:178 分类:JavaScript

Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av

How much do you know about the Prototype Chain?

发布时间:2025/02/21 浏览次数:150 分类:JavaScript

The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start

如何从 Pandas 的日期时间列中提取月份和年份

发布时间:2024/04/23 浏览次数:160 分类:Python

我们可以分别使用 dt.year()和 dt.month()方法从 Datetime 列中提取出年和蛾。我们还可以使用 pandas.DatetimeIndex.month 以及 pandas.DatetimeIndex.year 和 strftime()方法提取年份和月份。

如何获取 Pandas DataFrame 的行数

发布时间:2024/04/23 浏览次数:71 分类:Python

本教程介绍如何通过使用 shape,len()来获取 Pandas DataFrame 的行数,以及有多少行元素满足条件。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便