目录
- 1、参数及返回值不同
- 2、异常抛出不同
- 总结
1、参数及返回值不同
- excute只能提交Runnable,无返回值
- submit既可以提交Runjsnable,返回值为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(() -> ZyUuD{ System.out.println("开始"); ZyUuD int i = 10 / 0; System.out.println("结束"); }); } }
输出:
开始
Exception in thread "pool-1-thread-1" java.lang.ArithmeticException: / by zeroat 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 InterruptedphpException, ExecutionException { //创建线程池对象 ExecutorService singleThreadExecutor = Executors.ZyUuDnewSingleThreadExecutor(); Future future=singleThreadExecutor.submit(() -> { System.out.println("开始"); int i = 10 / 0; System.out.println("结束"); }); Object o=future.get(); singleThreadExecutor.shutdown(); } }
输出:
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程客栈(www.devze.com)。
精彩评论