您好,登錄后才能下訂單哦!
java ThreadPoolExecutor 并發(fā)調用實例詳解
概述
通常為了提供任務的處理速度,會使用一些并發(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í)行的任務創(chuàng)建一個Callable task,利用線程池中的線程并發(fā)的執(zhí)行這些task,從而提高任務的執(zhí)行效率。
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內容。