As others have noted, replacing a simple for loop with a thread is not necessarily better for this specific example. However, benefits begin to emerge if the problem you are trying to solve is more general. For example, instead of repeating some specific code n times, suppose you need to repeat part of the code passed as a parameter? Consider:
void repeat(int count, Runnable action) { IntStream.range(0, count).forEach(i -> action.run()); }
Now you can write
repeat(3, () -> System.out.println("Hello!"));
or maybe
repeat(4, this::doStuff);
Perhaps instead of performing one action n times, you want to perform several actions n times. You can do something like this:
void repeat(int count, Runnable... actions) { IntStream.range(0, count).forEach(i -> Arrays.asList(actions).forEach(Runnable::run)); }
Then you can write:
repeat(5, this::doStuff, this::doMoreStuff, this::doEvenMoreStuff);
The repeat implementation is somewhat shorter (perhaps shorter) than the usual Java 7 way:
void repeatOldWay(int count, Runnable...actions) { for (int i = 0; i < count; i++) { for (Runnable r : actions) { r.run(); } } }
The real advantage comes from the call site, where you can simply pass the score and one or more lambda expressions or method references instead of replicating the logic of nested loops.
Stuart marks
source share