Given the definition:
class Sum implements Callable<Long> { // LINE_DEF long n;/*from www . j av a2 s .co m*/ public Sum(long n) { this.n = n; } public Long call() throws Exception { long sum = 0; for(long i = 1; i <= n; i++) { sum += i; } return sum; } }
Given that the sum of 1 to 5 is 15, select the correct option for this code segment:
Callable<Long> task = new Sum(5); ExecutorService es = Executors.newSingleThreadExecutor(); // LINE_FACTORY Future<Long> future = es.submit(task); // LINE_CALL System.out.printf("sum of 1 to 5 is %d", future.get()); es.shutdown();
d)
this code correctly uses Callable<T>, ExecutorService, and Future<T> interfaces and the Executors class to calculate the sum of numbers from 1 to 5.