使用ExecutorService的各个线程的时间限制 [英] Time limit on individual threads with ExecutorService

查看:395
本文介绍了使用ExecutorService的各个线程的时间限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ExecutorService管理一些Callables。 Callables运行的任务主要是黑盒转换和数字运算。在某些条件下,正在转换的数据将会振荡并且线程将花费一个多小时来完成。为了比较,大多数线程在一分钟内完成。

I have an ExecutorService managing a number of Callables. The tasks that the Callables run are mostly black box transformations and number crunching. Under certain conditions, the data being transformed will oscillate and the thread will take over an hour to finish. For comparison, most threads are completed within a minute.

已经发现长时间运行的线程中的数据并不相关。我想打断任何运行时间超过一定时间的线程。最好的方法是什么?

It's been deteremined that the data from the long-running threads is not relevent. I would like to interrupt any thread that runs longer than a certain amount of time. What would the best way to do this?

推荐答案

使用ScheduleExecutorService将任务安排到 taskFuture。取消(true)达到超时时长时间运行的任务。如果任务在此之前完成,则不会被取消。

Use a ScheduleExecutorService to schedule a task to taskFuture.cancel(true) the long running task when the timeout is reached. If the task finishes before then it won't be cancelled.

ExecutorService service = Executors.newFixedThreadPool(N);
ScheduledExecutorService canceller = Executors.newSingleThreadScheduledExecutor();

public <T> Future<T> executeTask(Callable<T> c, long timeoutMS){
   final Future<T> future = service.submit(c);
   canceller.schedule(new Callable<Void>(){
       public Void call(){
          future.cancel(true);
          return null;
       }
    }, timeoutMS, TimeUnit.MILLI_SECONDS);
   return future;
}

这篇关于使用ExecutorService的各个线程的时间限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆