如何从父线程中注意到异常?

tem*_*ame 5 java multithreading exception-handling executorservice

我正在喂一条线ExecutorService.

这些线程正在操作某些数据,如果存在冲突,则数据对象会抛出异常,该异常会被冲突的线程捕获,而后者又会中止并且不会完成执行.

发生这种情况时,需要将中止线程放回队列并反馈给执行程序.

如何从父线程中判断是否抛出了异常?

Thi*_*ler 11

当你submit()执行任务时,ExecutorService你会得到一个未来的结果.执行完成后,您可以召唤get()该未来.如果适用,这将返回结果,否则ExecutionException如果原始任务抛出一个,则抛出结果.如果你想要真正的异常对象,你可以做getCause().

另请注意,您将Task重新投入服务,该任务在Thread尚未真正终止的情况下运行(刚刚捕获异常并等待新的异常).

以下是一个示例用法(Runnable如果您不关心结果,则可以使用).

Callable<String> myCallable = ...;
Future<String> future = myExector.submit(myCallable);

// Do something else until myCallable.isDone() returns true.
try {
    String result = future.get();
}catch(ExecutionException e){
    // Handle error, perhaps create new Callable to submit.
}
Run Code Online (Sandbox Code Playgroud)