Simple Multi-Threading Example in Java
This week I spent some time figuring out how to use multiple threads in Java. Well, really, I just learned the basics. But it was enough to get a functional example working, and it took me less time than I anticipated. I won’t go into a lot of detail on how to do this because others have covered the details. But I did have a bit of a hard time finding a simple, functional example. So I’m providing that here. In the code below, an ArrayList containing String objects is instantiated. Then Callable objects are used to package the logic that will be executed on each string—in this case, it is simply to print the object. Then the Callable objects are executed as the threads become available. Note that I am configuring it to use as many threads as there are processors on the system, but you can specify the number of threads by hand if you prefer.
import java.util.*; import java.util.concurrent.*; public class Main { public static void main(String[] args) { ArrayList x = new ArrayList(); x.add("A"); x.add("B"); x.add("C"); Collection<Callable> callables = new LinkedList<Callable>(); for (String y : x) { callables.add(new Callable() { public Object call() throws Exception { System.out.println(y); } }); } ExecutorService service = newFixedThreadPool(Runtime.getRuntime().availableProcessors()); service.invokeAll(callables); service.shutdown(); } }
Another approach would be to use a handy tool called Conja by David Soergel. In this case, your code would be something more simple, like the code snippet below:
Parallel.forEach(x, new Function() { public Void apply(String obj) { System.out.println(obj); return null; } });
I haven’t used either method extensively, but I recommend starting with Conja, and if it works for you, go with that instead of the more raw approach.