首页 > 解决方案 > java - 如何在调用阻塞调用时释放当前线程并在调用返回时在java中的异步编码中继续

问题描述

我想在调用阻塞调用时释放当前线程,并在调用以 java 中的异步编码返回时继续。示例如下:

public class Thread1 implements Runnable {
    public void run() {
        someBlockingCall();  // when do this calling, I want the current thread can be relased to do some other stuff, like execute some other Runnable object
        getResult();  // when return from the blocking call, something can inform the thread to continue executing, and we can get the result
    }
}

我怎么能意识到这一点?请帮我。

标签: javamultithreadingblocking

解决方案


您需要显式someBlockingCall()异步调用,然后阻塞以等待结果到期

public void run() {
    CompletableFuture<ResultType> result = 
             CompletableFuture.supplyAsync(() -> someBlockingCall());

    //do some other work here while someBlockingCall() is running async
    //this other work will be done by the first (main?) thread

    ResultType finalResult = result.join(); //get (or wait for) async result

    //Now use the result in the next call
    getResult();
}

如果someBlockingCall()有一个 void 返回类型,你可以使用CompletableFuture.runAsync(() -> someBlockingCall());, 未来是类型CompletableFuture<Void>


推荐阅读