Here you can find the source of runConcurrently(final Callable
Parameter | Description |
---|---|
task | a Callable to run concurrently. |
Parameter | Description |
---|---|
Exception | if any of the executed tasks fails. |
public static void runConcurrently(final Callable<Void> task, final int times) throws Exception
//package com.java2s; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class Main { /**/*from ww w. j a va2s . c o m*/ * Runs a task concurrently. Allows to test thread-safe behavior. * * @param task * a {@link Callable} to run concurrently. * @throws Exception * if any of the executed tasks fails. */ public static void runConcurrently(final Callable<Void> task, final int times) throws Exception { final ExecutorService service = Executors.newFixedThreadPool(5); final List<Future<?>> futures = new ArrayList<Future<?>>(); for (int i = 0; i < times; i++) { futures.add(service.submit(task)); } for (final Future<?> future : futures) { future.get(); } } public static void runConcurrently(final Callable<Void>... tasks) throws Exception { final ExecutorService service = Executors.newFixedThreadPool(5); final List<Future<?>> futures = new ArrayList<Future<?>>(); for (final Callable<Void> task : tasks) { futures.add(service.submit(task)); } for (final Future<?> future : futures) { future.get(); } } /** * Run the task concurrently 50 times. */ public static void runConcurrently(final Callable<Void> task) throws Exception { runConcurrently(task, 50); } }