java - 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
}
}
我怎么能意识到这一点?请帮我。
解决方案
您需要显式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>
推荐阅读
- iis - IIS Windows 身份验证在 SERVER 上不断提示
- angular - ag-grid 单元格编辑只允许数字
- javascript - React 中的获取请求:如何映射对象数组中的 JSON 对象数组?
- javascript - 带 TS 的 Redux Toolkit:调度两个连续异步 thunk 操作的推荐方法是什么
- iis - 通过 Cloudflare 连接到 Zoom API 的问题
- java - @SpringBootApplication 注解未在类路径中找到 bean
- datatables - 数据表排序问题(而不是第一行取第二行进行排序)
- html - 如何使 CSS 多行打字机效果响应?
- android - 无法膨胀行为子类 com.google.android.material.transition.MaterialContainerTransform
- javascript - 什么类型的 import 语句用于从 ES6 转译到 ES5 的文件?