3

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.

2
  • 1
    For one thing, there's no way to control the level of parallelism. For another, it doesn't compile. Commented Oct 14, 2016 at 6:18
  • 1
    If you are doing threads and using java 8, have you considered CompletableFuture its a much more useful api for running threads and much easier to manage them. Commented Oct 14, 2016 at 8:51

2 Answers 2

2

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();
Sign up to request clarification or add additional context in comments.

Comments

2

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
 } );
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.