> Java > java지도 시간 > 본문

완료 가능향후 사용량

DDD
풀어 주다: 2024-08-15 14:15:30
원래의
258명이 탐색했습니다.

CompletableFuture를 사용하여 여러 비동기 작업이 완료될 때까지 기다리는 방법?

CompletableFuture는 여러 비동기 작업이 완료될 때까지 기다리는 데 사용할 수 있는 allOf라는 메서드를 제공합니다. allOf 메서드는 가변 개수의 CompletableFuture 개체를 인수로 사용하고 CompletableFutureCompletableFuture를 반환합니다. /code> 객체가 완료되었습니다.allOf that can be used to wait for multiple asynchronous operations to complete. The allOf method takes a variable number of CompletableFuture objects as arguments and returns a new CompletableFuture that completes when all of the input CompletableFuture objects have completed.

The following code sample shows how to use the allOf method to wait for multiple asynchronous operations to complete:

<code class="java">CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> "Hello");
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "World");
CompletableFuture<Void> allOf = CompletableFuture.allOf(future1, future2);

allOf.join();

System.out.println(future1.get()); // Prints "Hello"
System.out.println(future2.get()); // Prints "World"</code>
로그인 후 복사

How does CompletableFuture's cancellation mechanism work?

CompletableFuture provides a cancel method that can be used to cancel the asynchronous operation represented by the CompletableFuture. The cancel method takes a boolean argument that indicates whether or not the cancellation should be interrupting.

If the cancel method is called with the interrupting flag set to true, the asynchronous operation will be interrupted if it is still running. If the asynchronous operation has already completed, the cancel method will have no effect.

If the cancel method is called with the interrupting flag set to false, the asynchronous operation will be cancelled if it has not yet completed. If the asynchronous operation has already completed, the cancel method will have no effect.

The following code sample shows how to use the cancel method to cancel an asynchronous operation:

<code class="java">CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return "Hello World";
});

future.cancel(true); // Interrupt the asynchronous operation

if (future.isCancelled()) {
    System.out.println("The asynchronous operation was cancelled.");
}</code>
로그인 후 복사

How to handle exceptions and return values with CompletableFuture?

CompletableFuture provides methods for handling both exceptions and return values. The thenApply and thenAccept methods can be used to handle return values, while the exceptionally and handle methods can be used to handle exceptions.

The thenApply method takes a function as an argument and returns a new CompletableFuture that will be completed with the result of applying the function to the result of the original CompletableFuture. The following code sample shows how to use the thenApply method to handle a return value:

<code class="java">CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hello World");

CompletableFuture<Integer> future2 = future.thenApply(s -> s.length());

future2.join();

System.out.println(future2.get()); // Prints 11</code>
로그인 후 복사

The thenAccept method takes a consumer as an argument and returns a new CompletableFuture that will be completed when the consumer has been applied to the result of the original CompletableFuture. The following code sample shows how to use the thenAccept method to handle a return value:

<code class="java">CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hello World");

CompletableFuture<Void> future2 = future.thenAccept(s -> System.out.println(s));

future2.join(); // Prints "Hello World"</code>
로그인 후 복사

The exceptionally method takes a function as an argument and returns a new CompletableFuture that will be completed with the result of applying the function to the exception that caused the original CompletableFuture to complete exceptionally. The following code sample shows how to use the exceptionally method to handle an exception:

<code class="java">CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
    throw new RuntimeException("Error!");
});

CompletableFuture<String> future2 = future.exceptionally(e -> "Error occurred: " + e.getMessage());

future2.join();

System.out.println(future2.get()); // Prints "Error occurred: java.lang.RuntimeException: Error!"</code>
로그인 후 복사

The handle method takes a bi-function as an argument and returns a new CompletableFuture that will be completed with the result of applying the bi-function to the result of the original CompletableFuture and the exception that caused the original CompletableFuture to complete exceptionally (if any). The following code sample shows how to use the handle

다음 코드 샘플은 allOf 메서드를 사용하여 여러 비동기 작업이 완료될 때까지 기다리는 방법을 보여줍니다.🎜
<code class="java">CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
    if (Math.random() > 0.5) {
        return "Success";
    } else {
        throw new RuntimeException("Error!");
    }
});

CompletableFuture<String> future2 = future.handle((result, exception) -> {
    if (exception != null) {
        return "Error occurred: " + exception.getMessage();
    } else {
        return result;
    }
});

future2.join();

System.out.println(future2.get()); // Prints "Success" or "Error occurred: java.lang.RuntimeException: Error!"</code>
로그인 후 복사
🎜CompletableFuture의 취소 메커니즘은 어떻게 작동합니까?🎜🎜CompletableFuture는 다음을 제공합니다. CompletableFuture가 나타내는 비동기 작업을 취소하는 데 사용할 수 있는 cancel 메서드. cancel 메서드는 취소가 중단되어야 하는지 여부를 나타내는 부울 인수를 사용합니다.🎜🎜cancel 메서드가 true로 설정된 중단 플래그와 함께 호출되는 경우 , 비동기 작업이 아직 실행 중인 경우 중단됩니다. 비동기 작업이 이미 완료된 경우 cancel 메서드는 아무런 효과가 없습니다.🎜🎜cancel 메서드가 false로 설정된 중단 플래그와 함께 호출되는 경우 code>, 비동기 작업이 아직 완료되지 않은 경우 취소됩니다. 비동기 작업이 이미 완료된 경우 <code>cancel 메서드는 아무런 효과가 없습니다.🎜🎜다음 코드 샘플은 cancel 메서드를 사용하여 비동기 작업을 취소하는 방법을 보여줍니다.🎜 rrreee🎜CompletableFuture를 사용하여 예외 및 반환 값을 처리하는 방법은 무엇입니까?🎜🎜CompletableFuture는 예외 및 반환 값을 모두 처리하는 방법을 제공합니다. thenApplythenAccept 메서드를 사용하여 반환 값을 처리할 수 있으며, 예외적으로handle 메서드를 사용할 수 있습니다. 🎜🎜thenApply 메서드는 함수를 인수로 취하고, 그 결과에 함수를 적용한 결과로 완성될 새로운 CompletableFuture를 반환합니다. 원본 <code>CompletableFuture. 다음 코드 샘플은 thenApply 메서드를 사용하여 반환 값을 처리하는 방법을 보여줍니다.🎜rrreee🎜 thenAccept 메서드는 소비자를 인수로 사용하고 새 를 반환합니다. 원래 <code>CompletableFuture의 결과에 소비자가 적용될 때 완료되는 CompletableFuture입니다. 다음 코드 샘플은 thenAccept 메서드를 사용하여 반환 값을 처리하는 방법을 보여줍니다.🎜rrreee🎜 예외적으로 메서드는 함수를 인수로 사용하고 새 를 반환합니다. 원본 <code>CompletableFuture가 예외적으로 완료되도록 만든 예외에 함수를 적용한 결과로 완료되는 CompletableFuture입니다. 다음 코드 샘플은 예외적으로 메서드를 사용하여 예외를 처리하는 방법을 보여줍니다.🎜rrreee🎜 handle 메서드는 이중 함수를 인수로 사용하고 새 CompletableFuture는 원본 CompletableFuture의 결과에 이중 함수를 적용한 결과와 원본 CompletableFuture를 완료하게 만든 예외입니다. 예외적으로(있는 경우). 다음 코드 샘플은 handle 메서드를 사용하여 반환 값이나 예외를 처리하는 방법을 보여줍니다.🎜rrreee

위 내용은 완료 가능향후 사용량의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!