Java异步调用目标输出的方法

Jia*_*ang 10 java asynchronous

假设我有一个check如下调用的阻塞方法:

boolean check(String input) {}
Run Code Online (Sandbox Code Playgroud)

这将对输入进行一些检查并返回决定。

现在我想对输入列表异步运行此检查,并且我想在其中一个输入通过检查后立即返回主线程,因此我不必等待所有异步调用完成。等待所有线程完成的唯一一种情况是没有输入通过检查。使用输入列表异步运行该方法很简单,但我不确定在获取通过检查的输入的目标输出后如何返回主线程。

Sni*_*nix 5

这是一个非常简单的工作示例来实现您的要求

Future<Boolean> future = CompletableFuture.runAsync(() -> {
    // Do your checks, if true, just return this future
    System.out.println("I'll run in a separate thread than the main thread.");
});

// Now, you may want to block the main thread waiting for the result
while(!future.isDone()) {
    // Meanwhile, you can do others stuff
    System.out.println("Doing other stuff or simply waiting...");
}

// When future.isDone() returns, you will be able to retrieve the result
Boolean result = future.get();
Run Code Online (Sandbox Code Playgroud)