如何在调用阻塞调用时释放当前线程并在java中的异步编码中调用returns时继续

How to release current thread when invoking a blocking call and continue when the call returns in asynchronous coding in java

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

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
    }
}

我怎样才能意识到这一点?请帮助我。

您需要显式地异步调用 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 return类型,你可以使用CompletableFuture.runAsync(() -> someBlockingCall());,将来是CompletableFuture<Void>

类型

综上所述,目前我在这个问题中所写的想法没有办法实现,因为你不能让两个并行语句在两个不同的线程中执行。