java - 等待来自其他线程的回调
问题描述
首先,我决定让我的类阻塞(让消费者更容易使用——但对我来说可能写起来更乏味)。与让消费者定义异步回调相反。这是一个好的设计模式吗?这样,用户可以获得预期的行为,但如果他们对线程阻塞的时间不满意,则可以实现自己的多线程。
我有一个构造函数,它根据异步回调的结果在类中设置最终字段:
class Example {
private final int x;
Example(){
asyncFunc(/* callback */ result -> x = result)
}
}
这不起作用,所以我使用了原子引用,并实现了一个阻塞循环,直到它返回结果,如下所示:
class Example {
private final int x;
Example(){
x = waitAsyncFunc();
}
private int waitAsyncFunc(){
AtomicBoolean finished = new AtomicBoolean(false);
AtomicReference<byte[]> result = new AtomicReference<>();
asyncFunc(result -> {
result .set(res);
finished.set(true);
});
while (!finished.get()) { /* No op */ }
return result.get();
}
}
这是阻止/检索结果的好方法吗?
解决方案
最简单的解决方案是
class Example {
private final int x;
Example() {
CompletableFuture<Integer> f = new CompletableFuture();
asyncFunc(f::complete);
x = f.join();
}
}
Example
但是考虑在构建实例之前等待异步作业完成的替代方案。
推荐阅读
- node.js - 我如何在heroku上部署这个项目?
- c# - 如何获取 .Net 5 PublishSingleFile 可执行路径(临时文件夹)
- javascript - 在页面上找不到动态元素
- python - Python Igraph 中的图联合
- assembly - 强制 LDR 指令将值放入 THUMB 程序集中的文字池中
- mongodb - 仅按需将数据从 MongoDB 发送到 Kafka 主题
- c - C中int数组的动态数组
- sqlite - 奇怪的 org.sqlite.SQLiteException: [SQLITE_ERROR] SQL 错误或缺少数据库(外键不匹配 -
- api - 如何在 Next js api 中使用不同的中间件来获取和发布方法?
- database - 我可以使用什么来构建用于访问和修改数据库的 GUI?