9

我想为在线程池中执行的线程设置超时。目前我有以下代码:

ExecutorService executor = Executors.newFixedThreadPool(8);
for(List<String> l: partition) {            
    Runnable worker = new WorkerThread(l);
    executor.execute(worker);
}       

executor.shutdown();
while (!executor.isTerminated()) {

}

该代码只是将一个大对象列表拆分为子列表,并在单个线程中处理这些子列表。但这不是重点。

我想给线程池中的每个线程一个超时。对于池中只有一个线程,我找到了以下解决方案:

Future<?> future = null;

for (List<String> l : partition) {
    Runnable worker = new WorkerThread(l);
    future = executor.submit(worker);
}

try {
    System.out.println("Started..");
    System.out.println(future.get(3, TimeUnit.SECONDS));
    System.out.println("Finished!");
} catch (TimeoutException e) {
    System.out.println("Terminated!");
}

但这不适用于一个以上的线程。也许我必须将每个线程放在一个List<Future>列表中并遍历该列表并为每个future对象设置超时?

有什么建议么?

使用 CountDownLatch 后编辑:

CountDownLatch doneSignal = new CountDownLatch(partition.size());
List<Future<?>> tasks = new ArrayList<Future<?>>();
ExecutorService executor = Executors.newFixedThreadPool(8);
for (List<String> l : partition) {
    Runnable worker = new WorkerThread(l);
    tasks.add(executor.submit(doneSignal, worker));
}

doneSignal.await(1, TimeUnit.SECONDS);
if (doneSignal.getCount() > 0) {
    for (Future<?> fut : tasks) {
    if (!fut.isDone()) {
        System.out.println("Task " + fut + " has not finshed!");
        //fut.cancel(true) Maybe we can interrupt a thread this way?!
    }
    }
}

到目前为止效果很好。

那么下一个问题是如何中断一个超时的线程?我尝试fut.cancel(true)在工作线程的一些关键循环中添加以下构造:

if(Thread.interrupted()) {
    System.out.println("!!Thread -> " + Thread.currentThread().getName() + " INTERRUPTED!!");
        return;
}

所以工作线程在超时后被“杀死”。这是一个好的解决方案吗?

此外:是否可以获取接口超时的线程名称Future?目前我必须在Thread.interrupted()构造的 if 条件中打印出名称。

感谢帮助!

问候

4

1 回答 1

3

你见过这个吗?ExecutorService.invokeAll

这应该正是您想要的:调用一组工作人员,如果花费时间过长,让他们超时。

评论后编辑 - (新想法):您可以使用CountDownLatch等待任务完成和超时await(long timeout, TimeUnit unit)!然后,您甚至可以执行 shutdownNow 并查看哪些任务花费了太长时间......

编辑2:

为了更清楚:

  1. 完成后,让每个 Worker 倒计时一个 CountDownLatch。
  2. await在所述锁存器上有超时的主执行线程中。
  3. 当该调用返回时,您可以检查锁存器的计数以查看是否有超时命中(如果它>0)。
  4. a) count = 0,所有任务按时完成。b)如果没有,循环 Futures 并检查它们的isDone. 您不必在 ExecutorService 上调用 shutdown。
  5. 如果您不再需要 Executor,请调用 shutdown。

注意:Worker 可以在超时和调用 Future 的 isDone() 之间完成。

于 2013-01-09T14:06:55.680 回答