java如何设置等待时间设置
设置等待时间的常见方法
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或响应式编程模型







