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

时间:2016-05-02 01:55:17

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

3 个答案:

答案 0 :(得分:4)

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 :(得分:1)

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

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

答案 2 :(得分:1)

  

我想在主线程上执行onSuccess()方法。我该如何解决这个问题。

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