经过很长一段时间后我又回到Java了,如果这个问题看起来很愚蠢,我会道歉。我正在尝试使用 CompletableFuture 来创建非阻塞调用。我有一个返回布尔值的方法
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)
即使我将函数的返回类型更改为Boolean或Integer,错误仍然存在,所以我确定我正在调用 CompletableFuture
答案 0 :(得分:1)
你应该给它一个供应商,所以不要调用内联方法,而是将它作为lambda表达式:
CompletableFuture<Boolean> resultHandle =
CompletableFuture.supplyAsync(() ->
this.waitOnState("RUNNING", 100000));
() -> this.waitOnState("RUNNING", 100000)
是一个lambda表达式,编译器可以从中创建Supplier
,但this.waitOnState("RUNNING", 100000)
是一个布尔表达式。