java ThreadPoolExecutor 并發(fā)調(diào)用實(shí)例詳解
java ThreadPoolExecutor 并發(fā)調(diào)用實(shí)例詳解
概述
通常為了提供任務(wù)的處理速度,會(huì)使用一些并發(fā)模型,ThreadPoolExecutor中的invokeAll便是一種。
代碼
package test.current; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; public class TestCallable { public static void main(String[] args) throws InterruptedException, ExecutionException { List<Callable<List<Long>>> tasks = new ArrayList<>(); for (int i = 0; i < 10; i++) { Callable<List<Long>> task = new Callable<List<Long>>() { @Override public List<Long> call() throws Exception { return Arrays.asList(1L,2L); } }; tasks.add(task); } List<Long> finalResults = new ArrayList<>(10); List<Future<List<Long>>> results = ThreadPool.getThreadPool().invokeAll(tasks); for(Future<List<Long>> ele : results) { List<Long> list = ele.get(); finalResults.addAll(list); } System.out.println(finalResults); } }
package test.current; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class ThreadPool { private static final int CORE_SIZE = 8; private static final int MAX_SIZE = 12; private static final long KEEP_ALIVE_TIME = 30; private static final int QUEUE_SIZE = 50000; private static ThreadPoolExecutor threadPool = new ThreadPoolExecutor(CORE_SIZE, MAX_SIZE, KEEP_ALIVE_TIME, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(QUEUE_SIZE), new ThreadPoolExecutor.AbortPolicy()); public static ThreadPoolExecutor getThreadPool() { return threadPool; } }
可以把需要執(zhí)行的任務(wù)創(chuàng)建一個(gè)Callable task,利用線程池中的線程并發(fā)的執(zhí)行這些task,從而提高任務(wù)的執(zhí)行效率。
感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
相關(guān)文章
MultipartResolver實(shí)現(xiàn)文件上傳功能
這篇文章主要為大家詳細(xì)介紹了MultipartResolver實(shí)現(xiàn)文件上傳功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-06-06Java實(shí)現(xiàn)聯(lián)系人管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了Java實(shí)現(xiàn)聯(lián)系人管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-02-02Java內(nèi)存溢出的幾個(gè)區(qū)域總結(jié)(注意避坑!)
內(nèi)存溢出是指應(yīng)用系統(tǒng)中存在無法回收的內(nèi)存或使用的內(nèi)存過多,最終使得程序運(yùn)行要用到的內(nèi)存大于虛擬機(jī)能提供的最大內(nèi)存,下面這篇文章主要給大家介紹了關(guān)于Java內(nèi)存溢出的幾個(gè)區(qū)域,總結(jié)出來給大家提醒注意避坑,需要的朋友可以參考下2022-11-11SpringBoot項(xiàng)目打包發(fā)布到外部tomcat(出現(xiàn)各種異常的解決)
這篇文章主要介紹了SpringBoot項(xiàng)目打包發(fā)布到外部tomcat(出現(xiàn)各種異常的解決),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09