submit()返回Future可获取结果和状态,execute()无返回值不关心结果。submit支持Callable并能处理异常,execute仅支持Runnable且异常默认被忽略。

核心区别在于
submit()
Future
execute()
解决方案
submit()
execute()
ExecutorService
submit()
submit()
Runnable
Callable
submit()
Future<?>
Future
Future
future.get()
get()
future.isDone()
future.cancel(boolean mayInterruptIfRunning)
Future
future.get()
ExecutionException
getCause()
execute()
execute()
Runnable
execute()
UncaughtExceptionHandler
代码示例
import java.util.concurrent.*;
public class ThreadPoolExample {
public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newFixedThreadPool(2);
// 使用 submit() 提交 Runnable 任务
Future<?> futureRunnable = executor.submit(() -> {
System.out.println("Runnable task running");
// 模拟耗时操作
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
// 使用 submit() 提交 Callable 任务
Future<String> futureCallable = executor.submit(() -> {
System.out.println("Callable task running");
// 模拟耗时操作
try {
Thread.sleep(500);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return "Callable result";
});
// 使用 execute() 提交 Runnable 任务
executor.execute(() -> {
System.out.println("Execute task running");
});
// 获取 Callable 任务的结果
try {
String result = futureCallable.get(); // 阻塞直到任务完成
System.out.println("Callable result: " + result);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
executor.shutdown();
executor.awaitTermination(1, TimeUnit.MINUTES);
}
}副标题1
submit()
execute()
submit()
Future
future.get()
ExecutionException
getCause()
相比之下,
execute()
execute()
Runnable
副标题2
什么时候应该使用
submit()
execute()
使用 submit()
使用 execute()
Future
选择哪个方法取决于具体的业务需求和对任务执行结果的关注程度。
副标题3
submit()
execute()
在资源管理方面,
submit()
execute()
不过,由于
submit()
Future
future.get()
因此,在选择使用哪个方法时,需要综合考虑任务的执行结果、异常处理和资源管理等因素。
以上就是线程池中 submit()和 execute()方法有什么区别?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号