import java.util.LinkedList;
import java.util.List;
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 InvokeAllAndAnyTest {
public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService pool = Executors.newCachedThreadPool();
List<Callable<Integer>> tasks = new LinkedList<Callable<Integer>>();
for (int i = 0; i < 8; ++i) {
tasks.add(new Printer(i));
}
List<Future<Integer>> futures = pool.invokeAll(tasks); // 阻塞直至所有线程计算结束.
System.out.println("...............................................");
for (Future<Integer> future : futures) {
System.out.println(future.get());
}
Integer result = pool.invokeAny(tasks); // 阻塞直至随机一个线程计算结束.
System.out.println("...............................................");
System.out.println(result);
pool.shutdown();
}
}
class Printer implements Callable<Integer> {
private int id;
private static final int DELAY = 1000;
public Printer(int id) {
this.id = id;
}
public Integer call() {
try {
int times = 10;
for (int i = 0; i < times; ++i) {
System.out.println("Id:" + id + " times:" + i);
Thread.sleep((int) (DELAY * Math.random()));
}
} catch (InterruptedException e) {
}
return id;
}
}