线程池之exectue与submit的区别及说明
作者:Ahuuua
这篇文章主要介绍了线程池之exectue与submit的区别及说明,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
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(); } }
输出:
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。