【发布时间】:2023-03-28 20:32:01
【问题描述】:
我遇到以下问题:
主线程运行我的应用程序的代码(每秒被调用几次),并且在某些时候它会在执行某个操作之前通知一个侦听器列表。然后侦听器执行操作以从外部源收集数据,其中一些操作非常耗时。
现在,一方面我想让每个侦听器有机会在我继续运行主线程之前完成它的工作(因为在操作完成后数据可能会丢失或更改),另一方面我需要将整个通知收集过程限制为某个超时,以保持操作的合理流程。
无论如何,我希望任何没有时间完成工作的听众继续。
一些示例代码:
public class ExampleTimeoutNotifier {
private static ArrayList<ExampleTimeoutNotifierListener> listeners;
private static int timeOutInMillis;
public static void main(String[] args) {
timeOutInMillis = Integer.parseInt(args[0]);
// ... the following code is being called repeatedly on the main thread:
// How to limit the process timeout?
for (ExampleTimeoutNotifierListener l : listeners) {
l.collectBeforeAction();
}
// Do the action...
}
public interface ExampleTimeoutNotifierListener {
public void collectBeforeAction();
}
}
【问题讨论】:
-
如果我理解你的意思,也许你应该看看同步。这里docs.oracle.com/javase/tutorial/essential/concurrency/…
-
@CME64 你能解释一下这有什么帮助吗?我没有并发问题,也不关心锁定任何对象或数据。
-
这就是我从你的陈述中理解的“我想让每个听众有机会在我继续运行主线程之前完成它的工作(因为数据可能会在操作之后丢失或更改)完成)”如果我错了请纠正我
-
哦,等一下,你想在线程执行完后继续在主体中运行吗? ,,在这种情况下,它不应该是一个线程,而是一个函数会这样做
标签: java multithreading timeout listener