Rumah  >  Artikel  >  Java  >  penggunaan masa hadapan yang lengkap

penggunaan masa hadapan yang lengkap

DDD
DDDasal
2024-08-15 14:15:30259semak imbas

Bagaimana untuk menggunakan CompletableFuture untuk menunggu beberapa operasi async selesai?

CompletableFuture menyediakan kaedah yang dipanggil allOf yang boleh digunakan untuk menunggu beberapa operasi tak segerak selesai. Kaedah allOf mengambil bilangan pembolehubah CompletableFuture sebagai argumen dan mengembalikan CompletableFuture baharu yang lengkap apabila semua input CompletableFuture objek telah selesai.<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

Sampel kod berikut menunjukkan cara menggunakan kaedah allOf untuk menunggu beberapa operasi tak segerak selesai:🎜
<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>
🎜Bagaimana mekanisme pembatalan CompletableFuture berfungsi?🎜🎜CompletableFuture menyediakan kaedah batal yang boleh digunakan untuk membatalkan operasi tak segerak yang diwakili oleh CompletableFuture. Kaedah batal mengambil hujah boolean yang menunjukkan sama ada pembatalan harus mengganggu atau tidak.🎜🎜Jika kaedah batal dipanggil dengan bendera mengganggu ditetapkan kepada true , operasi tak segerak akan terganggu jika ia masih berjalan. Jika operasi tak segerak telah selesai, kaedah batal tidak akan mempunyai kesan.🎜🎜Jika kaedah batal dipanggil dengan bendera mengganggu ditetapkan kepada false code>, operasi tak segerak akan dibatalkan jika ia masih belum selesai. Jika operasi tak segerak telah selesai, kaedah <code>batal tidak akan mempunyai kesan.🎜🎜Sampel kod berikut menunjukkan cara menggunakan kaedah batal untuk membatalkan operasi tak segerak:🎜 rrreee🎜Bagaimana untuk mengendalikan pengecualian dan mengembalikan nilai dengan CompletableFuture?🎜🎜CompletableFuture menyediakan kaedah untuk mengendalikan kedua-dua pengecualian dan nilai pulangan. Kaedah thenApply dan thenAccept boleh digunakan untuk mengendalikan nilai pulangan, manakala kaedah exceptionally dan handle boleh digunakan untuk mengendalikan pengecualian.🎜🎜Kaedah thenApply mengambil fungsi sebagai hujah dan mengembalikan CompletableFuture baharu yang akan dilengkapkan dengan hasil penggunaan fungsi pada hasil CompletableFuture asal. Contoh kod berikut menunjukkan cara menggunakan kaedah thenApply untuk mengendalikan nilai pulangan:🎜rrreee🎜Kaedah thenAccept mengambil pengguna sebagai hujah dan mengembalikan baharu CompletableFuture yang akan dilengkapkan apabila pengguna telah digunakan pada hasil CompletableFuture asal. Contoh kod berikut menunjukkan cara menggunakan kaedah thenAccept untuk mengendalikan nilai pulangan:🎜rrreee🎜Kaedah exceptionally mengambil fungsi sebagai hujah dan mengembalikan baharu CompletableFuture yang akan dilengkapkan dengan hasil penggunaan fungsi pada pengecualian yang menyebabkan CompletableFuture asal selesai dengan luar biasa. Contoh kod berikut menunjukkan cara menggunakan kaedah exceptionally untuk mengendalikan pengecualian:🎜rrreee🎜Kaedah handle menggunakan dwifungsi sebagai hujah dan mengembalikan CompletableFuture yang akan dilengkapkan dengan hasil penggunaan dwifungsi pada hasil CompletableFuture asal dan pengecualian yang menyebabkan CompletableFuture asal selesai luar biasa (jika ada). Contoh kod berikut menunjukkan cara menggunakan kaedah handle untuk mengendalikan nilai pulangan atau pengecualian:🎜rrreee

Atas ialah kandungan terperinci penggunaan masa hadapan yang lengkap. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn