Napisałem program, który tworzy trzy listy i sprawdza ile czasu to zajmuje. Wygląda tak:
public class Main {
public static void main(String[] args) throws ExecutionException, InterruptedException {
createThreeLists();
}
public static void createThreeLists() {
long start = System.currentTimeMillis();
List<String> converted1 = createList();
List<String> converted2 = createList();
List<String> converted3 = createList();
long stop = System.currentTimeMillis();
System.out.println("Time: " + (stop - start));
}
private static List<String> createList() {
List<String> toReturn = new ArrayList<>();
for (int i = 0; i < 10000000; i++)
toReturn.add("heheszki");
return toReturn;
}
}
Wykonanie teko programu zajmuje na moim komputerze ~750ms
A tak wygląda program z użyciem ExecutorService i Future:
public class Main {
public static void main(String[] args) throws ExecutionException, InterruptedException {
createThreeArrays();
}
public static void createThreeArrays() throws ExecutionException, InterruptedException {
long start = System.currentTimeMillis();
ExecutorService executor = Executors.newFixedThreadPool(3);
Future<List<String>> f1 = executor.submit(getCallable());
Future<List<String>> f2 = executor.submit(getCallable());
Future<List<String>> f3 = executor.submit(getCallable());
List<String> converted1 = f1.get();
List<String> converted2 = f2.get();
List<String> converted3 = f3.get();
long stop = System.currentTimeMillis();
System.out.println("Time: " + (stop - start));
}
private static Callable<List<String>> getCallable() {
Callable<List<String>> callable = () -> {
List<String> toReturn = new ArrayList<>();
for (int i = 0; i < 10000000; i++)
toReturn.add("heheszki");
return toReturn;
};
return callable ;
}
}
Jego wykonanie zajmuje dwa razy więcej czasu.
Czy użycie Futurenie powinno przyspieszyć jego działania?
Shalom