Simulate generating thumbnails for 8 images on a fixed pool of 4 threads (each takes 50 ms); collect each image's thumbnail size through Futures in order and print the results and total.
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class Main {
static int makeThumbnail(String file) throws InterruptedException {
Thread.sleep(50); // pretend to resize the image
return file.length() * 10; // pretend thumbnail size in KB
}
public static void main(String[] args) throws Exception {
String[] files = {"a.jpg", "beach.png", "cat.gif", "dog.jpg", "e.png", "forest.jpg", "g.bmp", "home.png"};
long start = System.nanoTime();
List<Future<Integer>> sizes = new ArrayList<>();
try (ExecutorService pool = Executors.newFixedThreadPool(4)) {
for (String f : files) sizes.add(pool.submit(() -> makeThumbnail(f)));
}
int total = 0;
for (int i = 0; i < files.length; i++) {
int kb = sizes.get(i).get();
total += kb;
System.out.printf("%-11s %3d KB%n", files[i], kb);
}
long ms = (System.nanoTime() - start) / 1_000_000;
System.out.println("total " + total + " KB, faster than sequential (400 ms): " + (ms < 350));
}
}
a.jpg 50 KB beach.png 90 KB cat.gif 70 KB dog.jpg 70 KB e.png 50 KB forest.jpg 100 KB g.bmp 50 KB home.png 80 KB total 560 KB, faster than sequential (400 ms): true
Eight 50 ms tasks on four threads take about 100 ms instead of 400 ms; reading Futures in order keeps the output stable.