这种方法有什么问题吗?
public static void runinParallel(final List<Runnable> tasks){
tasks.parallelStream().forEach(t -> t.run());
}假设并行执行任务是安全的。
发布于 2016-10-14 13:28:46
您可以使用一个任务列表和一个ExecutorService来执行以下操作
List<Task> tasks = new ArrayList<Task>();
ExecutorService threadPool = Executors.newFixedThreadPool(5);在添加所有你想要在并行线程中运行的任务之后,新的fixedThreadPool参数指定了想要并行运行的线程的数目,所以如果你有10个任务,5将首先运行,然后完成执行的线程将转移到下一个任务。您也可以使用cachedThreadPool。
然后将这些任务提交给ExecutorService
for (Task t : tasks) {
threadPool.submit(t);
}然后记得关闭线程池。
threadPool.shutdown();发布于 2016-10-14 15:27:34
是的,你能做到。这是一种更实用的方法,但请记住,您将无法控制所调用的线程。考虑使用java.util.concurrent.Future而不是Runnable
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
} );
}https://stackoverflow.com/questions/40035448
复制相似问题