car*_*ier 15 java concurrency multithreading callable
我有一个方法,我想打电话.但是,我正在寻找一种干净,简单的方法来杀死它或强迫它返回,如果执行时间太长.
我正在使用Java.
为了显示:
logger.info("sequentially executing all batches...");
for (TestExecutor executor : builder.getExecutors()) {
logger.info("executing batch...");
executor.execute();
}
Run Code Online (Sandbox Code Playgroud)
我认为TestExecutor
班级应该implement Callable
继续向这个方向发展.
但我想要做的就是停止,executor.execute()
如果它花了太长时间.
建议...?
编辑
收到的许多建议都假设正在执行的方法需要很长时间才能包含某种循环,并且可以定期检查变量.然而,这种情况并非如此.因此,某些东西不一定是干净的,只会停止执行,这是可以接受的.
Ale*_*lex 11
你应该看一下这些类: FutureTask,Callable,Executors
这是一个例子:
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");
}
}
}
Run Code Online (Sandbox Code Playgroud)
我假设在以下语句中使用多个线程.
我已经在这个领域做了一些阅读,大多数作者说杀死另一个线程是个坏主意.
如果要杀死的函数可以设计为定期检查变量或同步原语,然后在设置了该变量或同步原语时干净地终止,那将非常干净.然后某种监视器线程可以休眠几毫秒,然后设置变量或同步原语.
归档时间: |
|
查看次数: |
8379 次 |
最近记录: |