我想調用一個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