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.
Solution
Main.java
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));
}
}
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!