What time do you use the Callable object to call call () in Java Executor?
•
Java
Here are some sample code for example What I need to know is when calling call () on calllable? What triggered it?
public class CallableExample { public static class WordLengthCallable implements Callable { private String word; public WordLengthCallable(String word) { this.word = word; } public Integer call() { return Integer.valueOf(word.length()); } } public static void main(String args[]) throws Exception { ExecutorService pool = Executors.newFixedThreadPool(3); Set<Future<Integer>> set = new HashSet<Future<Integer>>(); for (String word: args) { Callable<Integer> callable = new WordLengthCallable(word); Future<Integer> future = pool.submit(callable); //**DOES THIS CALL call()?** set.add(future); } int sum = 0; for (Future<Integer> future : set) { sum += future.get();//**OR DOES THIS CALL call()?** } System.out.printf("The sum of lengths is %s%n",sum); System.exit(sum); } }
Solution
Once the callable is submitted, the executor schedules the callable for execution Depending on the executing program, this may happen directly or after the thread is available
On the other hand, the call to get only waits to retrieve the calculation result
Therefore, to be precise: between the intermediate submission being called and the call return, the call can be called
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码