我有一个我想调用的方法。然而,我正在寻找一种干净、简单的方法来杀死它,或者在执行时间太长的情况下强制它返回。
我正在使用Java。
为了显示:
logger.info("sequentially executing all batches...");
for (TestExecutor executor : builder.getExecutors()) {
logger.info("executing batch...");
executor.execute();
}
我算出TestExecutor
类应该implement Callable
并继续朝这个方向发展。
但我只想停下来executor.execute()
如果时间太长。
建议...?
EDIT
收到的许多建议都假设正在执行的需要很长时间的方法包含某种循环,并且可以定期检查变量。
然而,这种情况并非如此。因此,某些不一定是干净的并且只会在任何地方停止执行的东西是可以接受的。
你应该看看这些类:未来任务 http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/FutureTask.html, Callable http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/Callable.html, 执行者 http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/Executors.html
这是一个例子:
public class TimeoutExample {
public static Object myMethod() {
// does your thing and taking a long time to execute
return someResult;
}
public static void main(final String[] args) {
Callable<Object> callable = new Callable<Object>() {
public Object call() throws Exception {
return myMethod();
}
};
ExecutorService executorService = Executors.newCachedThreadPool();
Future<Object> task = executorService.submit(callable);
try {
// ok, wait for 30 seconds max
Object result = task.get(30, TimeUnit.SECONDS);
System.out.println("Finished with result: " + result);
} catch (ExecutionException e) {
throw new RuntimeException(e);
} catch (TimeoutException e) {
System.out.println("timeout...");
} catch (InterruptedException e) {
System.out.println("interrupted");
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)