1、参数及返回值不同
- excute只能提交runnable,无返回值
- submit既可以提交runnable,返回值为null,也可以提交callable,返回值future
excute:

submit:

2、异常抛出不同
- execute执行任务时遇到异常会直接抛出
- submit执行任务是遇到异常不会直接抛出,只有在使用future的get方法获取返回值时才会抛出异常
execute:
import org.junit.test;
import java.util.concurrent.*;
public class threadpooldemo {
@test
public void test() throws interruptedexception, executionexception {
//创建线程池对象
executorservice singlethreadexecutor = executors.newsinglethreadexecutor();
singlethreadexecutor.execute(() -> {
system.out.println("开始");
int i = 10 / 0;
system.out.println("结束");
});
}
}输出:
开始
exception in thread "pool-1-thread-1" java.lang.arithmeticexception: / by zero
at threadpooldemo.lambda$test$0(threadpooldemo.java:13)
at java.util.concurrent.threadpoolexecutor.runworker(threadpoolexecutor.java:1149)
at java.util.concurrent.threadpoolexecutor$worker.run(threadpoolexecutor.java:624)
at java.lang.thread.run(thread.java:748)
submit:
import org.junit.test;
import java.util.concurrent.*;
public class threadpooldemo {
@test
public void test() throws interruptedexception, executionexception {
//创建线程池对象
executorservice singlethreadexecutor = executors.newsinglethreadexecutor();
singlethreadexecutor.submit(() -> {
system.out.println("开始");
int i = 10 / 0;
system.out.println("结束");
});
}
}输出:
开始
submit 增加future的get方法
import org.junit.test;
import java.util.concurrent.*;
public class threadpooldemo {
@test
public void test() throws interruptedexception, executionexception {
//创建线程池对象
executorservice singlethreadexecutor = executors.newsinglethreadexecutor();
future future=singlethreadexecutor.submit(() -> {
system.out.println("开始");
int i = 10 / 0;
system.out.println("结束");
});
object o=future.get();
singlethreadexecutor.shutdown();
}
}
输出:

总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论