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

标签 java asynchronous

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

boolean check(String input) {}

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

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

最佳答案

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

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异步调用用于目标输出的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62293246/

相关文章:

java - 使用 Jersey 在运行时决定同步或异步响应

javascript - React组件类,不能写async方法?

c# - WPF 4.5 中的 INotifyDataErrorInfo 和异步数据验证

c# - 取消异步检索 URL 的任务

java - 如何查找并调试实际代码行 Java 错误 : Fatal Exception: java. lang.IndexOutOfBoundsException:

java - 如何在泛型方法中检查泛型类型

java - 使用命名空间生成的 Jaxb cxf-xjc 插件

java - 如何使用java持久性重试锁等待超时?

java - 使用条件表达式而不使用循环表达式的原因是什么?

c# - 单元测试异步方法 - 测试永远不会完成