首页 文章

如何在Java中实现非阻塞期货

提问于
浏览
2

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()方法 . 我怎样才能解决这个问题 . 谢谢

3 回答

  • 3

    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
            }
        });
    

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

  • 1

    Future 的要点是相关的计算是在一个单独的线程中执行的 . onSuccess 方法是该单独线程表示它已完成执行计算的一种方法 . 主线程调用 onSuccess 是没有意义的,因为主线程不知道计算何时完成 .

    从主线程,如果要等待计算完成并获得结果,请调用 get() . 如果要检查计算是否完成并继续执行其他操作(如果尚未完成),请调用 isDone()get(long, TimeUnit) . 如果要终止计算是否完成,请调用 cancel() .

  • 1

    我想在主线程上执行onSuccess()方法 . 我怎样才能解决这个问题 .

    你不能 . Java中的任何内容都不能使线程停止它正在做的事情,暂时做其他事情,然后回到它正在做的事情 . 一些编程环境具有类似的功能--- Unix信号,硬件中断---但它不是Java语言的一部分 .

相关问题