자바8to11

CompletableFuture

lby132 2022. 12. 23. 15:32
//비동기로 작업 실행하기 리턴타입이 없는 경우 runAsync
final CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
    System.out.println("Hello " + Thread.currentThread().getName());
});
future.get();

//비동기로 작업 실행하기 리턴타입이 있는 경우 runAsync
final CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
    System.out.println("Hello " + Thread.currentThread().getName());
    return "Hello";
});
System.out.println(future1.get());

CompletableFuture<String> hello = CompletableFuture.supplyAsync(() -> {
    System.out.println("Hello " + Thread.currentThread().getName());
    return "Hello";
});

final CompletableFuture<String> world = CompletableFuture.supplyAsync(() -> {
    System.out.println("World " + Thread.currentThread().getName());
    return "World";
});

final CompletableFuture<String> future2 = hello.thenCombine(world, (h, w) -> h + " " + w);
System.out.println("future2 = " + future2.get());

List<CompletableFuture> futures = Arrays.asList(hello, world);
final CompletableFuture[] futuresArray = futures.toArray(new CompletableFuture[futures.size()]);

final CompletableFuture<List<Object>> result = CompletableFuture.allOf(futuresArray)
        .thenApply(v -> futures.stream()
                    .map(CompletableFuture::join)
                    .collect(Collectors.toList()));

final List<Object> objects = result.get();

final CompletableFuture<Void> future3 = CompletableFuture.anyOf(hello, world).thenAccept(System.out::println);
future3.get();

'자바8to11' 카테고리의 다른 글

메서드참조  (0) 2022.12.30
Executors  (0) 2022.12.22
Date  (0) 2022.12.21
stream, optional  (0) 2022.12.20
함수형 인터페이스  (0) 2022.12.18