当前位置:首页 > Java

java如何设置等待时间设置

2026-03-03 21:59:19Java

设置等待时间的常见方法

Thread.sleep()方法
使用Thread.sleep(long millis)让当前线程暂停执行指定毫秒数。需处理InterruptedException
示例代码:

try {
    Thread.sleep(2000); // 等待2秒
} catch (InterruptedException e) {
    Thread.currentThread().interrupt();
}

ScheduledExecutorService
通过线程池实现更精确的定时任务控制,支持延迟执行和周期性任务。
示例代码:

ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.schedule(() -> {
    System.out.println("延迟3秒执行");
}, 3, TimeUnit.SECONDS);
executor.shutdown();

TimeUnit枚举
提供更可读的时间单位转换,常与sleep结合使用。
示例代码:

java如何设置等待时间设置

try {
    TimeUnit.SECONDS.sleep(1); // 等待1秒
} catch (InterruptedException e) {
    Thread.currentThread().interrupt();
}

在Selenium中的显式等待

WebDriverWait
结合ExpectedConditions实现动态等待元素出现。
示例代码:

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("elementId")));

FluentWait
提供更灵活的等待配置,可自定义轮询间隔和忽略异常。
示例代码:

java如何设置等待时间设置

Wait<WebDriver> fluentWait = new FluentWait<>(driver)
    .withTimeout(Duration.ofSeconds(30))
    .pollingEvery(Duration.ofSeconds(5))
    .ignoring(NoSuchElementException.class);
fluentWait.until(d -> d.findElement(By.linkText("Submit")));

在异步编程中的等待

CompletableFuture延迟
使用thenApplyAsync结合延迟执行异步任务。
示例代码:

CompletableFuture.supplyAsync(() -> "任务")
    .thenApplyAsync(s -> s + "结果", CompletableFuture.delayedExecutor(2, TimeUnit.SECONDS))
    .thenAccept(System.out::println);

CountDownLatch
通过倒计数器实现多线程间的同步等待。
示例代码:

CountDownLatch latch = new CountDownLatch(1);
new Thread(() -> {
    try {
        Thread.sleep(3000);
        latch.countDown();
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
}).start();
latch.await(); // 主线程等待子线程完成

注意事项

  • 避免在UI线程中使用Thread.sleep()导致界面卡顿
  • 显式等待优于隐式等待,减少不必要的等待时间
  • 异步场景推荐使用CompletableFuture或响应式编程模型

分享给朋友:

相关文章

如何设置java环境变量

如何设置java环境变量

下载并安装JDK 从Oracle官网下载适合操作系统的JDK安装包,运行安装程序并按照提示完成安装。安装过程中记下JDK的安装路径,通常默认路径为C:\Program Files\Java\jdk-版…

react如何设置input

react如何设置input

设置 React 中的 Input 元素 在 React 中设置 input 元素可以通过多种方式实现,包括受控组件、非受控组件以及使用第三方库。以下是几种常见的方法: 受控组件方式 受控组件通过…

vue实现时间刻度

vue实现时间刻度

Vue实现时间刻度组件 时间刻度组件常用于时间轴、日程管理或数据可视化场景。以下是基于Vue的实现方案: 基础时间刻度实现 使用v-for循环生成刻度元素,结合CSS实现布局: <templ…

vue实现时间滑块

vue实现时间滑块

Vue 实现时间滑块 使用原生 HTML5 input range 通过 HTML5 的 input[type="range"] 结合 Vue 的数据绑定实现基础时间滑块: <temp…

vue时间跨度实现

vue时间跨度实现

Vue 时间跨度实现方法 使用计算属性计算时间差 通过计算属性可以方便地计算两个日期之间的时间差。需要先定义开始和结束日期,然后在计算属性中进行计算。 computed: { timeDiffe…

react如何设置默认选中

react如何设置默认选中

设置默认选中状态的方法 在React中,可以通过组件的defaultValue或defaultChecked属性来设置默认选中状态,具体取决于使用的表单元素类型。 对于单选按钮(Radio)和复选框…