【问题标题】:How to set max execution time on individual tasks running on threads?如何为在线程上运行的单个任务设置最大执行时间?
【发布时间】:2020-05-06 04:19:23
【问题描述】:

我有一组多个级别的任务,我需要在从线程池中获取的线程上并行运行。

我正在使用倒计时锁来计时关卡的整体执行时间。

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

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

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】:

    一个可能的解决方案是设置一个在给定超时后将中断执行的任务。下面的例子可能会给你一个想法:

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

    您将需要一些代码在任务执行后取消超时处理程序。 详情请见ScheduledExecutorService#schelude

    【讨论】:

      猜你喜欢
      • 2021-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多