我想调用一个java中由于某种原因阻塞的方法。我想等待X分钟的方法,然后我想停止该方法。在java中调用超时的阻塞方法调用
我在StackOverflow上读到了一个解决方案,它给了我一个第一个快速入门。我写在这里: -
ExecutorService executor = Executors.newCachedThreadPool();
Callable<Object> task = new Callable<Object>() {
public Object call() {
return something.blockingMethod();
}
};
Future<Object> future = executor.submit(task);
try {
Object result = future.get(5, TimeUnit.SECONDS);
} catch (TimeoutException ex) {
// handle the timeout
} catch (InterruptedException e) {
// handle the interrupts
} catch (ExecutionException e) {
// handle other exceptions
} finally {
future.cancel(); // may or may not desire this
}
但现在我的问题是,我的函数可以抛出一些异常,我必须赶上并相应地做一些工作。因此,如果在代码中的功能blockingMethod()thorws一些异常如何在外部类中捕获它们?
我会在动物课上接受它。这样就不会有例外。 – 2012-07-06 13:15:08
另外,不要明确地捕获每个检查的异常,因为你可能不会写任何特定的处理代码。只要写'catch(RuntimeException e){throw e; } catch(Exception e){抛出新的RuntimeException(e); }' – 2012-07-06 13:24:46
是的,早些时候我认为同样的事情,我会这样做,但有很多外部类的变量,我想在异常处理代码中使用。而且我无法访问Inner类中的这些变量。 – 2012-07-06 13:32:32