【问题标题】:How to wait for multiple listeners with timeout如何等待多个侦听器超时
【发布时间】: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


【解决方案1】:

这是我正在使用的代码,它似乎工作得很好。 我暂时不会将其标记为我的选择,因为我不确定我的做法是否正确......

final long startTime = System.currentTimeMillis();
ArrayList<Thread> threads = new ArrayList<Thread>();

for (final ExampleTimeoutNotifierListener l : listeners) {
    Thread t = new Thread() {
        @Override
        public void run() {
            try {
                l.collectBeforeAction();
            } catch (Exception e) {}
        }
    };
    t.start();
    threads.add(t);
}

for (Thread t : threads) {
    try {
        long timeoutLeft = timeOutInMillis - (System.currentTimeMillis() - startTime);
        if (timeoutLeft < 1) break;
        t.join();
    } catch (InterruptedException e) {}
}

【讨论】:

    猜你喜欢
    • 2018-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-21
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    相关资源
    最近更新 更多