当前位置:首页 > 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结合使用。
示例代码:

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
提供更灵活的等待配置,可自定义轮询间隔和忽略异常。
示例代码:

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如何设置等待时间设置

分享给朋友:

相关文章

jquery时间

jquery时间

jQuery 时间处理 jQuery 本身不提供专门的时间处理函数,但可以通过 JavaScript 的 Date 对象结合 jQuery 的事件和方法来实现时间操作。以下是常见的时间处理需求及实现方…

react如何设置input

react如何设置input

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

vue实现滚动时间

vue实现滚动时间

Vue 实现滚动时间的方法 在 Vue 中实现滚动时间可以通过多种方式完成,以下是几种常见的方法: 使用 CSS 动画和 Vue 数据绑定 通过 Vue 的数据绑定和 CSS 动画结合,可以…

vue 时间控件实现

vue 时间控件实现

vue 时间控件实现 使用 Element UI 的 DatePicker Element UI 提供了功能丰富的日期选择组件,支持单日、日期范围、时间选择等场景。安装 Element UI 后,可以…

vue实现当前时间

vue实现当前时间

实现当前时间的Vue方法 在Vue中获取并显示当前时间可以通过以下方式实现: 方法一:使用data属性 new Vue({ el: '#app', data: { curren…

vue实现时间显示

vue实现时间显示

实现时间显示的基本方法 在Vue中显示时间可以通过多种方式实现,包括使用原生JavaScript的Date对象、第三方库如moment.js或day.js。以下是几种常见的方法。 使用原生Java…