[java] 람다 표현식을 사용하여 비동기 프로그래밍은 어떻게 할 수 있나요?

자바에서 람다 표현식은 간편한 비동기 프로그래밍을 가능케 합니다. 람다 표현식을 사용하면 코드 블록을 익명 함수로 간결하게 표현할 수 있으며, 이는 병렬 처리 및 비동기 작업에 유용합니다.

1. Runnable 및 Callable을 이용한 비동기 처리

// Runnable을 이용한 비동기 처리
new Thread(() -> {
    // 비동기 작업 수행
}).start();

// Callable과 Future를 이용한 비동기 처리
ExecutorService executor = Executors.newFixedThreadPool(1);
Future<String> future = executor.submit(() -> {
    // 비동기 작업 수행 후 결과 반환
    return "비동기 작업 완료";
});
// 결과 얻기
String result = future.get();
executor.shutdown();

2. CompletableFuture를 이용한 비동기 처리

CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
    // 비동기 작업 수행 후 결과 반환
    return "비동기 작업 완료";
});
// 결과 얻기
future.thenAccept(result -> System.out.println("결과: " + result));

3. Reactive Streams를 이용한 비동기 처리

Flowable.fromCallable(() -> {
    // 비동기 작업 수행 후 결과 반환
    return "비동기 작업 완료";
})
.subscribe(result -> System.out.println("결과: " + result));

이처럼 람다 표현식을 이용하여, Runnable, Callable, Future, CompletableFuture, Reactive Streams 등을 적절히 활용하여 비동기 프로그래밍을 구현할 수 있습니다.

참고 자료