在计划运行ScheduleWithFixedDelay时,是否有可能进行主线程等待

发布于 2025-01-25 05:12:45 字数 557 浏览 4 评论 0原文

如果需要进行一些必要的步骤来处理更改的值,则我需要在整个Java程序中监视属性值是否已更改。

我已经使用了ScheduleWithFixedDelay服务来监视价值和观察者模式,以采取必要的措施。

ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
scheduledExecutorService.scheduleWithFixedDelay(() -> {
    myClass2.scanValueChanged();
},1,45, TimeUnit.SECONDS);

由于scheduledexecutorservice和主线程并行运行,所以当我在Scheduledexecutorservice处理时,Main方法运行执行代码的块,并且由于预期的结果而失败。

当我可以暂停主线程的运行 是否有办法?

I need to monitor the property value has changed or not throughout the java program run, if its value has changed in need to do some necessary steps to handle the changed value.

I have used scheduleWithFixedDelay service to monitor value and observer pattern to take necessary action.

ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
scheduledExecutorService.scheduleWithFixedDelay(() -> {
    myClass2.scanValueChanged();
},1,45, TimeUnit.SECONDS);

Since scheduledExecutorService and main thread run parallel, by the time I handled in scheduledExecutorService the main method runs executes the block of the code and fails with the expected outcome.

Is there a way when scheduledExecutorService is running that I can pause the main thread?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

骑趴 2025-02-01 05:12:45

只需使用主线程

,如果您的应用程序无事可做,那么为什么要使用执行程序服务?在没有其他工作的主线程中,不需要背景线程。

在主线程上呼叫myClass2.scanvaluechanged(),然后是thread.sleep(45 * 1_000),在重复直至满足条件的环中。

Just use the main thread

If your app has nothing else to do, then why use an executor service? With no other work for the main thread, there’s no need for background threads.

Call myClass2.scanValueChanged() on your main thread, followed by Thread.sleep( 45 * 1_000 ), in a loop that repeats until your condition is met.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文