Java awaiting Future result without blocking

时间:2017-05-16 09:36:40

标签: java java.util.concurrent

I have an application where by clicking buttons (that number is defined) user creates tasks (Callable) that do some calculations. I want to be able to react when the task is finished. Using Future.get() blocks the application. Is there any way to be able to react when the Callable returns the result?

private static void startTask(int i){
    try{
        Future<Integer> future = executor.submit(callables.get(i-1));
        ongoingTasks.put(i, future);
        awaitResult(future, i);
    }
    catch(Exception e){
        e.printStackTrace();
    }
}

private static void awaitResult(Future<?> future, int taskNo) throws InterruptedException, ExecutionException{
    System.out.println("result : " + future.get());

    JButton b = buttons.get(taskNo);
    b.setEnabled(false);
}

1 个答案:

答案 0 :(得分:3)

听起来你想要CompletableFuture。您有一个功能,它是一个提供价值的“供应商”。这是实际工作的功能。

然后你有一个函数,只要工人完成就接受那个值。

这都是异步的,所以其他一切都会继续,无论结果如何。

class Main
{
    private static Integer work() {
        System.out.println("work");
        return 3;
    }

    private static void done(Integer i) {
        System.out.println("done " + i);
    }

    public static void main (String... args)
    {
        CompletableFuture.supplyAsync(Main::work)  
                         .thenAccept(Main::done);

        System.out.println("end of main");
    }
}

示例输出:

end of main
work
done 3