Reputation: 31
Is there anything wrong with this method...
public static void runinParallel(final List<Runnable> tasks){
tasks.parallelStream().forEach(t -> t.run());
}
assuming that it is safe to execute tasks in parallel.
Upvotes: 3
Views: 7661
Reputation: 5700
yes you can do that. This is more functional way of doing things but keep it in mind that you will not have control over the threads invoked. Instead of Runnable
, consider using java.util.concurrent.Future
public static void runinParallel(final List<Future> tasks){
tasks.parallelStream().forEach(t -> { threadPool.submit(t);
// collect the tasks in a collection and use it for future references
} );
}
Upvotes: 2
Reputation: 19622
You can do something like this have a list of tasks and an ExecutorService
List<Task> tasks = new ArrayList<Task>();
ExecutorService threadPool = Executors.newFixedThreadPool(5);
After that add all the tasks you want to run in parallel threads , the new fixedThreadPool takes parameter which specifies the no of threads to want to run in parallel , so if you have 10 tasks 5 will run first and after that the thread that finishes execution will move on to the next task. you can also use a cachedThreadPool.
Then Submit these tasks to the ExecutorService
for (Task t : tasks) {
threadPool.submit(t);
}
and after that remeber to close the threadpool .
threadPool.shutdown();
Upvotes: 2