Java ThreadPoolExecutor 的 submit 和 execute 方法有什么区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4016091/
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-08-14 08:27:45  来源:igfitidea点击:

What is the difference between submit and execute method with ThreadPoolExecutor

javamultithreading

提问by virsir

I found there are two ways (submit and execute) to add a Runnable into a thread pool, what is the difference?

我发现有两种方式(提交和执行)将 Runnable 添加到线程池中,有什么区别?

采纳答案by ColinD

The difference is that executedoesn't return a Future, so you can't wait for the completion of the Runnableand get any exception it throws using that.

不同之处在于execute它不返回 a Future,因此您不能等待完成Runnable并使用它获得它抛出的任何异常。

回答by AdamH

Submit appears to be a more generic form of execute. In particular, submit returns a Future object that represents the result of the computation.

提交似乎是一种更通用的执行形式。特别是, submit 返回一个表示计算结果的 Future 对象。

ThreadPoolExecutor-1

线程池执行器-1

ThreadPoolExecutor -2

线程池执行器 -2

回答by Victor Sorokin

The submit(...)method is an executor framework extension introduced in ExecutorServiceinterface.

submit(...)方法是ExecutorService接口中引入的执行器框架扩展。

Its main difference from execute(Runnable)is that submit(...)can accept a Callable<V>(whereas execute()accepts only Runnable) and returns an instance of Future<V>, which you can use later in the caller to retrieve the result asynchronously (potentially blocking until the computation performed by the Callableis completed).

它与 的主要区别execute(Runnable)在于submit(...)可以接受 a Callable<V>(而execute()仅接受Runnable)并返回 的实例Future<V>,您可以稍后在调用者中使用它来异步检索结果(可能会阻塞,直到 执行的计算Callable完成)。