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

标签 java multithreading future executorservice nonblocking

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/

相关文章:

java - 计算字符串中的字母 Java

c++ - 在 C++ 中处理线程的创建/重用

java - 如何设置java.util.concurrent.Future的结果?

ios - 在 UITableView 中重新加载数据而不阻塞 UI

java - 线程在 notifyall() 之后没有返回

r - 从 R 实现的 promise 中获取值(value)

concurrency - Erlang 中的 future 和 promise

java - neo4j 一直报错并且无法运行,你能帮我解决它的错误吗?

Java MS SQL -> mySQL 转换

c# - 使用 JSON 序列化作为持久化机制而不是 RDB