java Callable 中的异常处理是如何完成的

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12305667/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 08:23:04  来源:igfitidea点击:

How is exception handling done in a Callable

javamultithreading

提问by user1649415

I understand that callable's call can throw the exception to the parent method calling it which is not the case with runnable.

我知道 callable 的调用可以向调用它的父方法抛出异常,而 runnable 则不是这种情况。

I wonder how because it's a thread method and is the bottommost method of the thread stack.

我想知道如何,因为它是一个线程方法,并且是线程堆栈的最底层方法。

回答by Denys Séguret

The point of Callableis to have your exception thrown to your calling thread, for example when you get the result of a Futureto which you submitted your callable.

Callable是让你抛出异常到你调用线程,例如,当你得到的结果Future您提交到callable

public class CallableClass implements Callable<String> {
...
}

ExecutorService executor = new ScheduledThreadPoolExecutor(5);
Future<Integer> future = executor.submit(callable);

try {
    System.out.println(future.get());
} catch (Exception e) {
    // do something
}

回答by main--

Callable.call()can'tbe the bottommost stack frame. It's always called by another method that will then catch the exception. Callableshould usually be used to asynchronously compute values and later get them with a Futureobject. The operation mightthrow an exception that is later rethrown when you try to get the Future's value.

Callable.call()不能是最底层的堆栈框架。它总是由另一个方法调用,然后将捕获异常。Callable通常应该用于异步计算值,然后用Future对象获取它们。该操作可能会抛出异常,稍后在您尝试获取Future的值时会重新抛出该异常。

Runnableis simply supposed to run an operation that doesn't return anything. All exception handling should be done within the Runnablebecause it's unclear how any exceptions thrown in Runnable.run()should be handled. (The exception from a Callableis usually returned to the caller with the Future)

Runnable只是应该运行一个不返回任何内容的操作。所有异常处理都应该在 内完成,Runnable因为不清楚Runnable.run()应该如何处理抛出的任何异常。(来自 a 的异常Callable通常用 返回给调用者Future