gpt4 book ai didi

java - 如何等待计划任务的第一次迭代完成?

转载 作者:行者123 更新时间:2023-12-02 03:28:22 24 4
gpt4 key购买 nike

我安排了一项重复任务。现在我希望主线程等待 ScheduledExecutorService 完成其第一次执行。我怎样才能做到这一点?

public void test1(){
refreshFunction(); /* This should block until task has executed once. */
/* Continue with main thread. */
...
}

public void refreshFunction() {
try {
scheduledExecutorService = Executors.newScheduledThreadPool(1);
scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
loadInfo();
}
}, 1, 5, TimeUnit.MINUTES);
logger.info(" : Completed refreshing information : "
+ new Timestamp(System.currentTimeMillis()));
} catch (Exception ex) {
ex.printStackTrace();
}
}

最佳答案

使用 CountDownLatch在线程之间进行协调。

final CountDownLatch latch = new CountDownLatch(1);
scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
loadInfo();
latch.countDown();
}
}, 1, 5, TimeUnit.MINUTES);
latch.await();

更好的方法可能是让计划任务在加载信息后执行回调以更新依赖于该信息的观察者。

关于java - 如何等待计划任务的第一次迭代完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38466768/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com