Java异步调用用于目标输出的方法 [英] Java asynchronously call a method for target output

查看:89
本文介绍了Java异步调用用于目标输出的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个称为 check 的阻止方法,如下所示:

Suppose I have a blocking method called check as follows:

boolean check(String input) {}

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

which will do some check against the input and return the decision.

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

Now I want to run this check against a list of inputs asynchronously, and I want to return to the main thread right after one of the inputs passing the check, so I don't have to wait for all asynchronous call to be completed. The only one scenario for waiting all threads to complete is that there are no inputs passing the check. Running the method asynchronously with list of inputs is straightforward but I'm not sure how to return to the main thread after getting the target output for the input passing the check.

推荐答案

这是一个非常简单的工作示例,可以满足您的要求

Here is a really simple working example to achieve what you are asking for

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();

这篇关于Java异步调用用于目标输出的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆