当前位置:首页 > 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或响应式编程模型

分享给朋友:

相关文章

vue实现滚动时间

vue实现滚动时间

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

vue实现时间格式

vue实现时间格式

时间格式化方法 在Vue中实现时间格式化通常使用JavaScript原生方法或第三方库如moment.js或day.js。以下是几种常见实现方式: 使用JavaScript原生方法 // 获取当前时…

react数据如何设置

react数据如何设置

设置React数据的常用方法 在React中,数据管理主要通过组件状态(state)和属性(props)实现,以下是几种核心方法: 使用useState钩子管理组件状态 适用于函数组件中的局部状态管…

react如何设置动画

react如何设置动画

在React中设置动画的常用方法 使用CSS Transition 通过CSS的transition属性实现简单动画效果。在React组件中直接添加CSS类或内联样式。 .box { trans…

react如何设置默认选中

react如何设置默认选中

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

react 中如何设置图片

react 中如何设置图片

使用 img 标签直接引入图片 在 React 中可以直接使用 HTML 的 img 标签,通过 src 属性指定图片路径。路径可以是本地文件或远程 URL。 function ImageCom…