CompletableFuture - 提供一个 returns 布尔值的方法来调用 supplyAsync

CompletableFuture - supply a method that returns bool value to supplyAsync call

我在很长一段时间后回到 Java 如果这个问题看起来很愚蠢,我深表歉意。我正在尝试使用 CompletableFuture 来创建非阻塞调用。我有一个方法 return 是一个布尔值

public boolean waitOnState(final String targetState, final long waitMs) {
        long begin = System.nanoTime()/1000000;
        synchronized (stateLock) {
            long elapsedMs = 0L;
            logger.debug(this.storeName + "-" + this.getStreamState().toString());
            while (!this.getStreamState().toString().equals(targetState)) {

                if (waitMs > elapsedMs) {
                    long remainingMs = waitMs - elapsedMs;
                    try {
                        logger.debug("Waiting on stream to be in run state in "+remainingMs);
                        stateLock.wait(remainingMs);
                    } catch (final InterruptedException e) {
                        // it is ok: just move on to the next iteration
                    }
                } else {
                    logger.debug("Cannot transit to target state");
                    return false;
                }
                elapsedMs = System.nanoTime()/1000000 - begin;
            }
            logger.debug("State is running - "+this.storeName);
            return true;
        }
    }

然后我以这种方式将此函数传递给 completedFuture:

CompletableFuture<Boolean> resultHandle = 
                CompletableFuture.supplyAsync(this.waitOnState("RUNNING", 100000));
        resultHandle.thenAccept(result -> System.out.println(result));

但是我得到一个错误The method supplyAsync(Supplier<U>) in the type *CompletableFuture* is not applicable for the arguments (boolean)

即使我将函数的 return 类型更改为 Boolean 或 Integer,错误仍然存​​在,所以我确定我错误地调用了 CompletableFuture

你应该给它一个供应商,所以不要调用内联方法,而是让它成为一个 lambda 表达式:

CompletableFuture<Boolean> resultHandle = 
            CompletableFuture.supplyAsync(() -> 
                 this.waitOnState("RUNNING", 100000));

() -> this.waitOnState("RUNNING", 100000) 是一个 lambda 表达式,编译器可以从中生成 Supplier,但 this.waitOnState("RUNNING", 100000) 是一个布尔表达式。