1. 程式人生 > 其它 >併發處理多工(CompletableFuture)

併發處理多工(CompletableFuture)

併發處理多工(CompletableFuture)

1.開啟多執行緒處理多工並返回結果
public class Demo1 {

  private static LongAdder longAdder = new LongAdder();

  public static void main(String[] args) throws ExecutionException, InterruptedException {
      List<CompletableFuture<List<String>>> completableFutureList = new ArrayList<>();
      for (int i = 0; i < 10; i++) {
          completableFutureList.add(CompletableFuture.supplyAsync(() -> {
              return getCamera();
          }));
      }

      CompletableFuture<Void> allFuture = CompletableFuture.allOf(completableFutureList.toArray(new CompletableFuture[completableFutureList.size()]));
      CompletableFuture<List<List<String>>> listCompletableFuture = allFuture.thenApply(v ->
              completableFutureList.stream().map(completableFuture -> {
                  try {
                      return completableFuture.get();
                  } catch (InterruptedException e) {
                      e.printStackTrace();
                  } catch (ExecutionException e) {
                      e.printStackTrace();
                  }
                  return null;
              }).collect(Collectors.toList())
      );
      CompletableFuture<List<String>> listCompletableFuture1 = listCompletableFuture.thenApply(camerasList -> {
          List<String> result = new ArrayList<>();
          camerasList.stream().forEach(cameras -> {
              if (cameras != null) {
                  result.addAll(cameras);
              }
          });
          return result;
      });
      List<String> cameras = listCompletableFuture1.get();
      System.out.println(cameras);
  }

  private static List<String> getCamera() {
      longAdder.add(1);
      long sum = longAdder.sum();
      System.out.println(sum + "=====方法呼叫");

      try {
          Thread.sleep(3000);
      } catch (InterruptedException e) {
          e.printStackTrace();
      }
      System.out.println(sum + "=====方法呼叫結束");
      return new ArrayList<String>() {{
          add("a:" + sum);
      }};
  }

}