Here is a sample Java code for Promise:

import java.util.concurrent.CompletableFuture;

public class PromiseExample {
    public static void main(String[] args) {
        CompletableFuture<String> promise = new CompletableFuture<>();
        
        // Set the promise value after 2 seconds
        new Thread(() -> {
            try {
                Thread.sleep(2000);
                promise.complete("Promise Fulfilled!");
            } catch (InterruptedException e) {
                promise.completeExceptionally(e);
            }
        }).start();
        
        // Wait for the promise to be fulfilled
        promise.thenAccept(value -> {
            System.out.println(value);
        }).join();
    }
}

In this example, we create a CompletableFuture object named promise. We then start a new thread that waits for 2 seconds before setting the promise value to "Promise Fulfilled!". We then use the thenAccept method to wait for the promise to be fulfilled and print the value when it is fulfilled. Finally, we use the join method to wait for the promise to be fulfilled before exiting the program.

promise sample java

原文地址: https://www.cveoy.top/t/topic/bwjP 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录