CompletionService

import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CompletionServiceDemo {
public static void main(String[] args) {
int nThreads = Runtime.getRuntime().availableProcessors() * 2;
ExecutorService pool = Executors.newFixedThreadPool(nThreads);
// ExecutorService pool = Executors.newCachedThreadPool();
CompletionService cs = new ExecutorCompletionService(
pool);

for (int i = 0; i < 1000; i++) {
final int j = i;
cs.submit(new Callable() {
@Override
public Integer call() throws Exception {
Thread.sleep((long)(Math.random() * 1000));
return j;
}
});
}

for (int i = 0; i < 1000; i++) {
try {
System.out.println(cs.take().get());
} catch (Exception e) {
e.printStackTrace();
}
}
pool.shutdown();
}
}

你可能感兴趣的:(java基础,java,线程)