2013-06-13 33 views
0

我有以下问题:如何等待多个听众超时

主线程中运行我的应用程序的代码(即是被称为几次每秒),并在某些时候它通知在执行特定操作之前听众列表。听众然后执行操作以从外部来源收集数据,其中一些操作是耗时的。

现在,一方面我想给每个听者一个机会,在我继续运行主线程之前完成它的工作(因为数据可能会在操作完成后丢失或更改),以及另一方面,我需要将整个通知 - 收集过程限制到一定的超时时间,以便保持合理的行动流程。

无论如何,我希望任何听众都没有时间去完成它的工作来继续。

一些示例代码:

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(); 
    } 
} 
+0

也许你应该考虑同步的,如果我明白你的意思。这里http://docs.oracle.com/javase/tutorial/essential/concurrency/syncmeth.html – CME64

+0

@ CME64你能解释一下这可以帮到什么吗?我没有并发问题,也不关心锁定任何对象或数据。 – Elist

+0

这就是我从你的陈述中理解的“我想让每个听众有机会在我继续运行主线程之前完成它的工作(因为数据可能会在操作完成后丢失或更改)”,请纠正我我错了 – CME64

回答

0

这是我使用的代码,它似乎工作得很好。 我不会将其标记为我的选择。现在,因为我不知道我在做正确的方式...

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) {} 
}