gpt4 book ai didi

java - 如何在 Java 中实现非阻塞 Future

转载 作者:行者123 更新时间:2023-12-02 06:19:28 29 4
gpt4 key购买 nike

Java Future 对象用于获取由并行线程(Executors)执行的异步计算的结果。我们调用 Future.get() 方法并等待结果准备好。此示例展示了一种从 Future 检索结果的非阻塞方式。 java-implement-java-non-blocking-futures

NonBlockingExecutor executor = new NonBlockingExecutor(Executors.newSingleThreadExecutor());

NonBlockingFuture<Integer> future = executor.submitNonBlocking(new Callable<Integer>() {

@Override
public Integer call() throws Exception {
String threadName = Thread.currentThread().getName();
System.out.println(threadName);
//print -> pool-1-thread-1
return 1;
}
});

future.setHandler(new FutureHandler<Integer>() {

@Override
public void onSuccess(Integer value) {
String threadName = Thread.currentThread().getName();
System.out.println(threadName);
//print -> pool-1-thread-1
}

@Override
public void onFailure(Throwable e) {
System.out.println(e.getMessage());
}
});

Thread.sleep(50000);

在此 onSuccess() 方法在并行执行完成后被调用。问题是 onSuccess() 方法没有在主线程上运行。我想在主线程上执行 onSuccess() 方法。我怎样才能解决这个问题。谢谢

最佳答案

CompletableFutures 支持此功能。

    CompletableFuture.runAsync(() -> {
String threadName = Thread.currentThread().getName();
System.out.println(threadName);
//print -> pool-1-thread-1
}).whenComplete((task, throwable) -> {
if(throwable != null) {
System.out.println(e.getMessage());
} else {
String threadName = Thread.currentThread().getName();
System.out.println(threadName);
//print -> pool-1-thread-1
}
});

这里需要注意的是, future 将在执行线程而不是提交线程上运行 whenComplete 任务。

关于java - 如何在 Java 中实现非阻塞 Future,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36974019/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com