線程池之exectue與submit的區(qū)別及說明
1、參數及返回值不同
- excute只能提交Runnable,無返回值
- submit既可以提交Runnable,返回值為null,也可以提交Callable,返回值Future
excute:
submit:
2、異常拋出不同
- execute執(zhí)行任務時遇到異常會直接拋出
- submit執(zhí)行任務是遇到異常不會直接拋出,只有在使用Future的get方法獲取返回值時才會拋出異常
execute:
import org.junit.Test; import java.util.concurrent.*; public class ThreadPoolDemo { @Test public void test() throws InterruptedException, ExecutionException { //創(chuàng)建線程池對象 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 { //創(chuàng)建線程池對象 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 { //創(chuàng)建線程池對象 ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor(); Future future=singleThreadExecutor.submit(() -> { System.out.println("開始"); int i = 10 / 0; System.out.println("結束"); }); Object o=future.get(); singleThreadExecutor.shutdown(); } }
輸出:
總結
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
springboot 在ftl頁面上使用shiro標簽的實例代碼
這篇文章主要介紹了springboot 在ftl頁面上使用shiro標簽的實例代碼,通過文字說明結合實例的形式給大家介紹的非常詳細,需要的朋友參考下吧2018-05-05servlet之session工作原理簡介_動力節(jié)點Java學院整理
這篇文章主要介紹了servlet之session工作原理簡介,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-07-07SpringBoot配置MyBatis-Plus實現增刪查改
本文主要介紹了SpringBoot配置MyBatis-Plus實現增刪查改,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-08-08Spring Boot監(jiān)聽Redis Key失效事件實現定時任務的示例
這篇文章主要介紹了Spring Boot監(jiān)聽Redis Key失效事件實現定時任務的示例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-04-04