在ExecutorService的提交和ExecutorService的执行之间进行选择 [英] Choose between ExecutorService's submit and ExecutorService's execute

查看:183
本文介绍了在ExecutorService的提交和ExecutorService的执行之间进行选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应如何选择 ExecutorService submit 执行,如果返回的值不是我关注的话?

How should I choose between ExecutorService's submit or execute, if the returned value is not my concern?

如果我同时测试两者,除了返回值之外,我没有看到两者之间有任何差异。

If I test both, I didn't see any differences among the two except the returned value.

ExecutorService threadExecutor = Executors.newSingleThreadExecutor();
threadExecutor.execute(new Task());







ExecutorService threadExecutor = Executors.newSingleThreadExecutor();
threadExecutor.submit(new Task());


推荐答案

异常/错误处理方面存在差异。

There is a difference concerning exception/error handling.

使用 execute()排队的任务生成一些 Throwable 将导致运行要调用的任务的 Thread UncaughtExceptionHandler 。默认 UncaughtExceptionHandler ,它通常会将 Throwable 堆栈跟踪打印到 System.err

A task queued with execute() that generates some Throwable will cause the UncaughtExceptionHandler for the Thread running the task to be invoked. The default UncaughtExceptionHandler, which typically prints the Throwable stack trace to System.err, will be invoked if no custom handler has been installed.

另一方面, Throwable 由排队的任务生成() Throwable 绑定到 Future 是通过调用 submit()生成的。在 Future 上调用 get()将抛出 ExecutionException 使用原始 Throwable 作为原因(可通过在$ code> ExecutionException上调用 getCause()进行访问/ code>)。

On the other hand, a Throwable generated by a task queued with submit() will bind the Throwable to the Future that was produced from the call to submit(). Calling get() on that Future will throw an ExecutionException with the original Throwable as its cause (accessible by calling getCause() on the ExecutionException).

这篇关于在ExecutorService的提交和ExecutorService的执行之间进行选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆