Usage scenario: In an interface request, some service logic processes multi-threaded tasks, obtains the processing results of all asynchronous tasks, and then performs service operations on the main thread.

The following example can be used with only minor modifications and encapsulation in actual use:

package com.xnyzc.lhy.mis.util.threadPoolUtil; /** * @author liuju * @create 2020-01-07 14:08 */ import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class ThreadPoolExecutorFutureDemo { private static final int CORE_POOL_SIZE = 6; private static final int MAX_POOL_SIZE = 10; private static final int QUEUE_CAPACITY = 200; private static final Long KEEP_ALIVE_TIME = 1L; Public static void main(String[] args) {public static void main(String[] args) {public static void main(String[] args) {public static void main(String[] args) {public static void main(String[] args) {public static void main(String[] args) executor = new ThreadPoolExecutor( CORE_POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_TIME, TimeUnit.SECONDS, new LinkedBlockingQueue<>(QUEUE_CAPACITY), new ThreadPoolExecutor.CallerRunsPolicy()); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-DD HH:mm:ss SSS"); List<Future<HashMap<String, String>>> futureList = new ArrayList<>(); List<Integer> List = new ArrayList<>();for(int i = 0; i < 1000; i++) { list.add(i); } // The following can be wrapped into a multithreaded processing methodfor(int i = 0; i < list.size(); I++) {Future<HashMap<String, String>> Future = executor.submit(new Callable<HashMap<String, String>>() { @Override public HashMap<String, String> call() throws Exception { System.out.println(Thread.currentThread().getName() +"The asynchronous task starts at.... :"+ simpleDateFormat.format(new Date())); Thread.sleep(500); System.out.println(Thread.currentThread().getName() +"The asynchronous task is completed, and the execution result is returned!!!!"+ simpleDateFormat.format(new Date())); // Sets the return result to calculate whether all threads have finished processingreturn new HashMap<String, String>(16) {
                        {
                            this.put("futureKey"."1"); }}; }}); futureList.add(future); } System.out.println("==== after submitting the asynchronous task, immediately return to the main thread and continue." + simpleDateFormat.format(new Date()));
        try {
            Thread.sleep(1000);
        } catch (
                InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("==== You need to obtain the execution result of the above asynchronous task." + simpleDateFormat.format(new Date()));
        boolean flag = true;
        while (flag) {
            if(! futureList.isEmpty()) { int count = 0;for(Future Future: futureList) {// If the asynchronous task is completed and not cancelled, the result is returnedif(future.isDone() && ! future.isCancelled()) { try { HashMap<String, String> futureResult = (HashMap<String, String>) future.get();if(! futureResult.get("futureKey").isEmpty() && futureResult.get("futureKey") != "") {
                                count = count + Integer.valueOf(futureResult.get("futureKey")); } } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); }}} // Determine whether all tasks have been processedif (count == list.size()) {
                    System.out.println("Result returned by ==== asynchronous task successful!" + simpleDateFormat.format(new Date()));
                    flag = false;
                }
            }
        }

        System.out.println("All missions completed!!"+ simpleDateFormat.format(new Date())); // Close the thread poolif(! executor.isShutdown()) { executor.shutdown(); }}}Copy the code

Running results: