当前位置:网站首页>The thread pool method opens the thread -- the difference between submit() and execute()
The thread pool method opens the thread -- the difference between submit() and execute()
2022-07-30 10:10:00 【silly fish love programming】
目录
1. The thread pool method starts the thread
1.1 创建线程池,And the code that starts the thread with the return value
1.2 创建线程池,And start a thread with no return value
2. submit()和execute()The difference between submitting tasks
2.1.2 submit提交任务,异常被吃,通过Future的get方法将任务执行时的异常重新抛出
2.2.1 executeSubmitted threads can passFutureTask获取线程结果
When there is no reference to the thread pool,We need to go through inheritanceThread类和实现Runnable、Callable接口,最终调用start()方法启动线程.
Want to understand the introduction of threads and thread pools,You can learn from this blog:多线程--Usage of threads and thread pools_Silly fish love programming blog-CSDN博客
Now we can pass the thread poolexecute()和submit()方法来提交线程任务.
1. The thread pool method starts the thread
Submitted tasks can optionally require a return value:
1.1 创建线程池,And the code that starts the thread with the return value
public static void main(String[] args) throws ExecutionException, InterruptedException {
int inter = 6;
System.out.println("The number of computer core threads = " + Runtime.getRuntime().availableProcessors());
// 创建线程池(自定义参数)
ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(
6,
10,
10L,
TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>(10),
new CustomizableThreadFactory(),
new ThreadPoolExecutor.CallerRunsPolicy());
// 定义线程数组(Thread collections can also be used)
FutureTask[] futureTask = new FutureTask[inter];
// 开启6个线程
for (int i = 0; i < inter; i++) {
futureTask[i] = new FutureTask<>(new Callable<String>() {
@Override
public String call() throws Exception {
// 模拟程序执行时间1S
Thread.sleep(1000);
System.out.println("线程数量activeCount = " + poolExecutor.getActiveCount());
System.out.println("排队数量size = " + poolExecutor.getQueue().size());
return "Callableexecuted in the thread pool.." + Thread.currentThread().getName();
}
});
// 线程池开启线程
poolExecutor.submit(futureTask[i]);
}
// 获取线程的执行结果
for (FutureTask task : futureTask) {
System.out.println("task返回结果 = " + task.get());
}
// 关闭线程池(The thread pool is not closed in real projects)
poolExecutor.shutdown();
}1.2 创建线程池,And start a thread with no return value
public static void main(String[] args) {
int inter = 6;
System.out.println("The number of computer core threads = " + Runtime.getRuntime().availableProcessors());
// 创建线程池(自定义参数)
ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(
5,
10,
10L,
TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>(10),
new CustomizableThreadFactory(),
new ThreadPoolExecutor.CallerRunsPolicy());
// 定义线程数组(Thread collections can also be used)
Runnable[] runnables = new Runnable[inter];
// 开启6个线程
for (int i = 0; i < inter; i++) {
runnables[i] = new Runnable() {
@Override
public void run() {
// 模拟程序执行
System.out.println("Add programs that need to be run===");
System.out.println("The total number of thread pool threads = " + poolExecutor.getPoolSize());
System.out.println("线程数量activeCount = " + poolExecutor.getActiveCount());
System.out.println("排队数量size = " + poolExecutor.getQueue().size());
}
};
// 线程池开启线程
poolExecutor.submit(runnables[i]);
}
// 关闭线程池(The thread pool is not closed in real projects)
poolExecutor.shutdown();
}2. submit()和execute()The difference between submitting tasks
| submit() | execute() | |
| 提交任务的类型 | 既能提交Runnable类型任务也能提交Callable类型任务 | 只能提交Runnable类型的任务() |
| 异常的处理方式 | 会吃掉异常.可通过Future的get方法将任务执行时的异常重新抛出 | 会直接抛出任务执行时的异常 |
| 是否有返回值 | 有返回值,It can be used when a return value is requiredsubmit | execute()没有返回值,可通过Future的get方法获取返回值 |
2.1 submit代码展示
源码展示(可以提交Callable类型和Runable类型):

2.1.1 submit提交任务,Abnormally eaten
public static void main(String[] args) {
int inter = 3;
// 创建线程池(自定义参数)
ExecutorService executorService = Executors.newFixedThreadPool(3);
// 定义线程数组(Thread collections can also be used)
Callable[] callables = new Callable[inter];
// 开启6个线程
for (int i = 0; i < inter; i++) {
callables[i] = new Callable<String>(){
@Override
public String call() throws Exception {
System.out.println("Add programs that need to be run===");
Thread.sleep(10*1000);
// 手动添加一个异常
int aa =1/0;
return "程序运行成功";
}
};
// 线程池开启线程
executorService.submit(callables[i]);
}
// 关闭线程池(The thread pool is not closed in real projects)
executorService.shutdown();
}控制台打印结果:无异常抛出

2.1.2 submit提交任务,异常被吃,通过Future的get方法将任务执行时的异常重新抛出
public static void main(String[] args) throws ExecutionException, InterruptedException {
int inter = 3;
// 创建线程池(自定义参数)
ExecutorService executorService = Executors.newFixedThreadPool(3);
// 定义线程数组(Thread collections can also be used)
Callable[] callables = new Callable[inter];
ArrayList<Future> futureTasks = new ArrayList<>();
// 开启6个线程
for (int i = 0; i < inter; i++) {
callables[i] = new Callable<String>(){
@Override
public String call() throws Exception {
System.out.println("Add programs that need to be run===");
Thread.sleep(10*1000);
// 手动添加一个异常
int aa =1/0;
return "程序运行成功";
}
};
// 线程池开启线程
Future submit = executorService.submit(callables[i]);
futureTasks.add(submit);
}
// 获取线程结果
for (Future futureTask : futureTasks) {
System.out.println("返回结果 = " + futureTask.get());
}
// 关闭线程池(The thread pool is not closed in real projects)
executorService.shutdown();
}控制台打印:异常被抛出

2.2 execute代码展示
源码展示(只能提交Runable类型):

2.2.1 executeSubmitted threads can passFutureTask获取线程结果
public static void main(String[] args) throws ExecutionException, InterruptedException {
int inter = 3;
// 创建线程池(自定义参数)
ExecutorService executorService = Executors.newFixedThreadPool(3);
// 定义线程数组(Thread collections can also be used)
FutureTask[] integerFuture = new FutureTask[inter];
// 开启6个线程
for (int i = 0; i < inter; i++) {
integerFuture[i] = new FutureTask<>(new Callable<Object>() {
@Override
public Object call() throws Exception {
System.out.println("Add programs that need to be run===");
Thread.sleep(10*1000);
return "程序返回的结果";
}
});
// 线程池开启线程
executorService.execute(integerFuture[i]);
}
// 通过FutureTask获取结果
for (FutureTask futureTask : integerFuture) {
System.out.println("fetched thread result:" + futureTask.get());
}
// 关闭线程池(The thread pool is not closed in real projects)
executorService.shutdown();
}总结:通过submit()和execute()源码可以看出submit封装了execute,If there are no special circumstances, it should be preferredexecute.因为execute效率会更高,Exceptions are also not eaten.
边栏推荐
- Two solutions for Excel xlsx file not supported
- mysql安装教程【安装版】
- els 方块、背景上色
- debian10 install djando
- 大数据产品:标签体系0-1搭建实践
- Re18: Read the paper GCI Everything Has a Cause: Leveraging Causal Inference in Legal Text Analysis
- Kotlin value class - value class
- 新一代开源免费的终端工具,太酷了
- 连接mysql报错WARN: Establishing SSL connection without server‘s identity verification is not recommended
- 读书笔记:《这才是心理学:看穿伪心理学的本质(第10版)》
猜你喜欢
随机推荐
唯物辩证法-条件论
Study Notes 11--Direct Construction of Local Trajectories
leetcode 剑指 Offer 25. 合并两个排序的链表
leetcode 剑指 Offer 47. 礼物的最大价值
0729放假自习
C语言顺序表基本操作
Use the R language to read the csv file into a data frame, and then view the properties of each column.
大根堆的创建(视频讲解)
leetcode 剑指 Offer 15. 二进制中1的个数
读书笔记:《这才是心理学:看穿伪心理学的本质(第10版)》
梅科尔工作室-看鸿蒙设备开发实战笔记六—无线联网开发
MySQL数据库题库
新一代开源免费的终端工具,太酷了
北京突然宣布,元宇宙重大消息
MySQL Explain usage and parameter detailed explanation
Unreal Engine Graphic Notes: could not be compiled. Try rebuilding from source manually. Problem solving
leetcode 剑指 Offer 46. 把数字翻译成字符串
大数据产品:标签体系0-1搭建实践
Jetpack Compose 从入门到入门(八)
你真的懂Redis的5种基本数据结构吗?









