本文介绍了是invoke 7()是Java 7中的阻塞调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ExecutorService executorService = Executors.newSingleThreadExecutor();

Set<Callable<String>> callables = new HashSet<Callable<String>>();

callables.add(new Callable<String>() {
    public String call() throws Exception {
        return "Task 1";
    }
});
callables.add(new Callable<String>() {
    public String call() throws Exception {
        return "Task 2";
    }
});
callables.add(new Callable<String>() {
    public String call() throws Exception {
        return "Task 3";
    }
});

List<Future<String>> futures = executorService.invokeAll(callables);

for(Future<String> future : futures){
    System.out.println("future.get = " + future.get());
}

对于此代码段.我的问题是"invokeAll()是否是阻塞调用"?我的意思是,当代码运行到invokeAll()行时,我们是否在此等待所有结果生成?

For this code piece. My question is "is invokeAll() a blocking call "?I mean, when code ran to invokeAll() line, are we bloking there to wait for all result been generated?

推荐答案

将来只能在执行完成后才能完成,因此,只有在执行任务后才能返回此方法.

Futures can only be done when execution is finished, therefore this method can only return when the tasks have been executed.

它可以引发InterruptedException也表示阻塞动作.

That it can throw an InterruptedException is also indicative of a blocking action.

java.util.concurrent.AbstractExecutorService中查看invokeAll的实现(内联注释):

Looking at the implementation of invokeAll in java.util.concurrent.AbstractExecutorService (comment inline):

public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
    throws InterruptedException {
    if (tasks == null)
        throw new NullPointerException();
    ArrayList<Future<T>> futures = new ArrayList<Future<T>>(tasks.size());
    boolean done = false;
    try {
        for (Callable<T> t : tasks) {
            RunnableFuture<T> f = newTaskFor(t);
            futures.add(f);
            execute(f);
        }
        for (int i = 0, size = futures.size(); i < size; i++) {
            Future<T> f = futures.get(i);
            if (!f.isDone()) {
                try {
                    f.get(); // <== *** BLOCKS HERE ***

                } catch (CancellationException ignore) {
                } catch (ExecutionException ignore) {
                }
            }
        }
        done = true;
        return futures;
    } finally {
        if (!done)
            for (int i = 0, size = futures.size(); i < size; i++)
                futures.get(i).cancel(true);
    }
}

实际上,在这些情况下,Javadoc-Specese似乎很难破译,通常应该看一下参考实现.

In fact, looking at a reference implementation is what you generally should do in these cases when the Javadoc-Specese appears to be difficult to decipher.

这篇关于是invoke 7()是Java 7中的阻塞调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 01:32