If we have the following requirements:

  1. Get all User ids from the User table in the database
  2. Query the information associated with all users based on their ids
  3. Once you get the information, process it
  4. After all user information is processed, complete the next step
  5. During processing, the main thread does not need to wait for the entire information to complete

Handle with Future:

Public class CompletableFutureTest {public static final String USER_MSG_FORMAT = "user info %d"; Public static final String USER_MSG_START_FORMAT = "Obtaining user information %d "; Public static final String USER_MSG_END_FORMAT = "obtain end "; private static ExecutorService executor = Executors.newFixedThreadPool(10); public static void main(String[] args) throws Exception { Future<List<Integer>> userIdListFuture = executor.submit(CompletableFutureTest::getUserIdList); mainThreadDo(); List<Integer> userIdList = userIdListFuture.get(); List<Future<String>> userMsg = new ArrayList<>(); userIdList.forEach(userId -> userMsg.add(executor.submit(() -> getUserMsg(userId)))); mainThreadDo(); for (Future<String> res : userMsg) { System.out.println(Thread.currentThread().getName() + " " + res.get()); } mainThreadDo(); executor.shutdown(); executor.awaitTermination(1, TimeUnit.DAYS); System.out.println(thread.currentThread ().getName() + "All services processed "); } public static void mainThreadDo() {system.out.println (thread.currentThread ().getName()); sleep(); System.out.println(thread.currentThread ().getName() + "Main Thread ends to execute other business logic "); } public static String getUserMsg(Integer userId) { System.out.println(Thread.currentThread().getName() + " " + String.format(USER_MSG_START_FORMAT, userId)); sleep(); System.out.println(Thread.currentThread().getName() + " " + USER_MSG_END_FORMAT); return String.format(USER_MSG_FORMAT, userId); } public static List<Integer> getUserIdList() { return Lists.newArrayList(1, 2, 3, 4, 5); } public static void sleep() {try {thread.sleep (500); } catch (InterruptedException e) { e.printStackTrace(); }}}Copy the code

Print result:

Main Main thread Start Perform other service logics Main main thread End Perform other service logics Main main thread Start perform other service logics Pool-1-thread-4 Is obtaining information about user 3. Pool-1-thread-3 is obtaining information about user 2 Pool-1-thread-2 Obtaining information about user 1 Pool-1-thread-5 Obtaining information about user 4 Pool-1-thread-6 Obtaining information about user 5 Main Main thread End Execute other service logic Pool-1-thread-4 Obtaining End Pool-1-thread-5 Obtaining End Pool-1-thread-6 obtaining End Pool-1-thread-3 Obtaining End Pool-1-thread-2 Obtaining End Main User information 1 main User information 2 Main user information 3 Main user information 4 Main user information 5 Main main thread Start Execute other service logics Main thread End Execute other service logics Main service processing is completeCopy the code

Handled by CompletableFuture:

public static void main(String[] args) throws Exception { System.out.println(Thread.currentThread().getName() + " Start and end of business "); List<CompletableFuture<Void>> completableFutureList = CompletableFuture. SupplyAsync (CompletableFutureTest2: : getUserIdList) / / getUserIdList encapsulated into Callable in ForkJoinPool execution .get () / / wait for the results. The stream (). The map (userId - > CompletableFuture. SupplyAsync (() - > ThenAccept (system.out ::println))// Convert stream List< userId > to List<CompletableFuture> .collect(Collectors.toList()); mainThreadDo(); // Wrap all List<CompletableFuture> into one CompletableFuture CompletableFuture<Void> CompletableFuture = CompletableFuture.allOf(completableFutureList.toArray(new CompletableFuture[0])); completableFuture.thenRun(() -> mainThreadDo()); // Install an end-of-execution callback for the encapsulated CompletableFuture as mainThreadDo() completableFuture.get(); Println (thread.currentThread ().getName() + "Business completed "); // Wait for completableFuture to complete. }Copy the code

CompletableFuture executes the callback sample diagram