如何在线程上运行的单个任务上设置最大执行时间?

问题描述 投票:0回答:1

我有一组多层任务,需要在从线程池中提取的线程上并行运行。

我正在使用倒数锁存器来计时该级别的整体执行。

问题:很少有任务比单独的时间执行更多的任务,这是因为存在于同一级别的其他任务具有更多的执行时间。我想避免这种情况。

下面是我正在使用的代码。

private final ExecutorService executor = Executors.newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat(
            "TaskExecutor-thread-%d").build());

....

for (int i = 0; i < levels.size(); i++) {

   Set<AbstractTask> taskSet = levels.get(i);
   CountDownLatch latch = new CountDownLatch(taskSet.size());

   int maxAwaitTime = TaskExecutorHelper.getMaxAwaitTime(taskSet);  //this returns max of all 
                                                                     // execution time set for 
                                                                      //individual tasks

   for (AbstractTask t : taskSet) {
                    executor.submit(() -> { t.doExecute(input); });
   } 

   latch.await(maxAwaitTime, TimeUnit.MILLISECONDS);

}

任何帮助将不胜感激!

java multithreading thread-safety threadpool multitasking
1个回答
0
投票

一种可能的解决方案是设置一个任务,该任务将在给定的超时后中断执行。以下示例可能会给您一个想法:

 private final ExecutorService executor = ...;
 private final ScheduledExecutorService scheduler = ...;

 Future future = executor.submit(() -> ... );
 ScheduledFuture scheduledFuture = scheduler.schedule(() -> future.cancel(true), 10, TimeUnit.SECONDS);

您将需要一些代码来在任务执行后取消超时处理程序。有关详细信息,请参见ScheduledExecutorService#schelude

© www.soinside.com 2019 - 2024. All rights reserved.