/ Published in: Java
A simple way to parallelize a for loop in Java. Wrapping each iteration (task) with a Runnable, executing them with an ExecutorService (to pool threads) and coordinating them with a simple CountDownLatch.
Due to Java's lack of closures, this simple scenario is rather verbose.
Due to Java's lack of closures, this simple scenario is rather verbose.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
ExecutorService executorService = Executors.newFixedThreadPool(5); int tasksCount = 10; final CountDownLatch latch = new CountDownLatch(tasksCount); for (int i = 0; i < tasksCount; i++ ) { public void run() { try { // Do some work; } finally { latch.countDown(); } } }); } try { latch.await(); // todo >> handle exception } // All done! // Do some more work }
URL: http://java.sun.com/j2se/1.6.0/docs/api/java/util/concurrent/CountDownLatch.html