import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class ExecutorServiceExample { private static final Random PRNG = new Random(); private static class Result { private final int wait; public Result(int code) { this.wait = code; } } public static Result compute(Object obj) throws InterruptedException { int wait = PRNG.nextInt(3000); Thread.sleep(wait); return new Result(wait); } public static void main(String[] args) throws InterruptedException, ExecutionException { List
有关更详细的解答,请阅读Java Concurrency in Practice并使用java.util.concurrent 。
这是我在自己的项目中使用的东西:
public class ParallelTasks { private final Collection tasks = new ArrayList(); public ParallelTasks() { } public void add(final Runnable task) { tasks.add(task); } public void go() throws InterruptedException { final ExecutorService threads = Executors.newFixedThreadPool(Runtime.getRuntime() .availableProcessors()); try { final CountDownLatch latch = new CountDownLatch(tasks.size()); for (final Runnable task : tasks) threads.execute(new Runnable() { public void run() { try { task.run(); } finally { latch.countDown(); } } }); latch.await(); } finally { threads.shutdown(); } } } // ... public static void main(final String[] args) throws Exception { ParallelTasks tasks = new ParallelTasks(); final Runnable waitOneSecond = new Runnable() { public void run() { try { Thread.sleep(1000); } catch (InterruptedException e) { } } }; tasks.add(waitOneSecond); tasks.add(waitOneSecond); tasks.add(waitOneSecond); tasks.add(waitOneSecond); final long start = System.currentTimeMillis(); tasks.go(); System.err.println(System.currentTimeMillis() - start); }