我遇到了一个关于ThreadPoolExecutor的问题。
在编写了一些代码后,我发现submit()方法将吃掉程序抛出的RuntimeException,但execute()方法将重新抛出RuntimeException`。我想知道这是什么原因。
我最近阅读了ThreadPoolExecutor的源代码,了解了线程池的原理。现在我理解了execute()方法是如何执行的,但是我不能理解submit()方法是如何执行的。我只知道submit()方法会将Runnable或Callable包装在FutureTask中并调用execute()方法:
public Future submit(Runnable runnable)
{
if(runnable == null)
{
throw new NullPointerException();
} else
{
RunnableFuture runnablefuture = newTaskFor(runnable, null);
execute(runnablefuture);
return runnablefuture;
}
}所以,我的问题是:ThreadPoolExecutor是如何执行FutureTask的,为什么RuntimeException会被吃掉?
发布于 2013-06-24 15:49:11
如果你研究一下newTaskFor方法,你会发现RunnableFuture实际上是java.util.concurrent.FutureTask的实例。您应该会在这个FutureTask类中看到run方法。
public void run() {
sync.innerRun();
} void innerRun() {
if (!compareAndSetState(READY, RUNNING))
return;
runner = Thread.currentThread();
if (getState() == RUNNING) { // recheck after setting thread
V result;
try {
result = callable.call();
} catch (Throwable ex) {
setException(ex);
return;
}
set(result);
} else {
releaseShared(0); // cancel
}
}捕获异常并将其设置为任务。调用FutureTask的get方法时会抛出包装到ExecutionException中
public V get() throws InterruptedException, ExecutionException {
return sync.innerGet();
}https://stackoverflow.com/questions/17262327
复制相似问题