We will be using ExecutorService from Executor framework and
Future interface to make asynchronous calls.
We will be using Streams from Java 8 to calculate the sum of
integers in the list.
import java.util.List;
import java.util.concurrent.Callable;
import java.util.stream.Collectors;
public class SumCalculator implements Callable
{
List inputList;
public SumCalculator(List
inputList){
this.inputList = inputList;
}
@Override
public Integer call() throws Exception {
return inputList.stream().collect(Collectors.summingInt(i->i));
}
}
import java.util.concurrent.Callable;
import java.util.stream.Collectors;
public class SumCalculator implements Callable
List
public SumCalculator(List
}
@Override
public Integer call() throws Exception {
return inputList.stream().collect(Collectors.summingInt(i->i));
}
}
Let’s split the list to 2 sublist and pass them to two different
threads so that the sum is calculated asynchronously and returned.
We will use future.get() to get the result from each thread
and combine to get the final total.
import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.stream.IntStream; public class ListSumAsync { public static void main(String...args){ ExecutorService executorService = Executors.newFixedThreadPool(2); ListintList = new ArrayList<>(); //Let us add 0 to 100 to a list IntStream.range(1, 11) .forEach(i -> intList.add(i)); //Let's split the list to 2 lists and pass // it to two threads and combine the result SumCalculator calculator1 = new SumCalculator(intList. subList(0,intList.size()/2)); Futureresult1 = executorService.submit(calculator1) ; SumCalculator calculator2 = new SumCalculator(intList.subList( (intList.size()/2),intList.size())); Futureresult2 = executorService.submit(calculator2) ; try { int total = result1.get().intValue()+ result2.get().intValue(); System.out.println("Total sum: "+total); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } }
No comments:
Post a Comment