java-8 - Java CompletableFuture - 主类未终止
问题描述
我正在尝试实现 CompletableFuture,它在完成时调用一个虚拟回调方法。
但是,在添加 CompletableFuture.get() 方法后,我的主类不会终止。我尝试用 Thread.sleep(5000) 替换 CompletableFuture.get() ,但这似乎不是正确的方法。请提出是什么导致 CompletableFuture.get() 即使线程完成也保持阻塞。
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.stream.IntStream;
public class CallableAsyncWithCallBack {
public static void main(String[] args) throws InterruptedException {
CompletableFuture<String> compFuture=new CompletableFuture<String>();
compFuture.supplyAsync(()->{
//Compute total
long count=IntStream.range(Integer.MIN_VALUE, Integer.MAX_VALUE).count();
return ""+count;
}).thenApply(retVal->{
try {
return new CallBackAsynchClass(retVal).toString();
} catch (InterruptedException | ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "";
}
);
System.out.println("Main Thread 1");
try {
compFuture.get();
} catch (ExecutionException e) {
e.printStackTrace();
}
System.out.println("Lock cleared");
}
}
class CallBackAsynchClass
{
String returnVal="";
public CallBackAsynchClass(String ret) throws InterruptedException, ExecutionException {
System.out.println("Callback invoked:"+ret);
returnVal=ret;
}
@Override
public String toString() {
return "CallBackAsynchClass [returnVal=" + returnVal + "]";
}
}
我期待输出“锁定已清除”,但 .get() 似乎正在阻止锁定。
解决方案
.thenApply
函数返回一个新CompletableFuture
的实例,你需要使用这个实例,尝试使用这种方式:
public class CallableAsyncWithCallBack {
public static void main(String[] args) throws InterruptedException {
CompletableFuture<String> compFuture = CompletableFuture.supplyAsync(() -> {
//Compute total
long count = IntStream.range(Integer.MIN_VALUE, Integer.MAX_VALUE).count();
return "" + count;
});
CompletableFuture<String> future = compFuture.thenApply(retVal -> {
try {
return new CallBackAsynchClass(retVal).toString();
} catch (InterruptedException | ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ""; });
System.out.println("Main Thread 1");
try {
future.get();
} catch (ExecutionException e) {
e.printStackTrace();
}
System.out.println("Lock cleared");
}
}
希望这可以帮助
推荐阅读
- r - 如何在 R 中自动化这个简单的条件列操作?
- redux - createSlice:Redux 存储访问在减速器和选择器之间有所不同?
- multithreading - 每个 CUDA 线程的本地内存
- wordpress - 将 IP 地址重定向到域 (Apache)
- python - 代理向我们确定的目的地发送数据包
- c - 使用暗网检测物体时输出警告音
- javascript - React:如果孩子是道具的一部分,那么为什么不重新渲染父母
- c# - 通过 GraphAPI 的 O365 用户邮箱使用量大小
- sql - 将字符串转换为数字而不会丢失精度和比例
- nsis - 有没有办法在 NSIS 脚本中链接 DetailPrint 中的部分文本以指向文件?