public class TestShutdown {
public static ExecutorService threadPool = Executors.newFixedThreadPool(5);
public static void main(String[] args) {
Long begin = System.currentTimeMillis();
//future.get()如果任务已完成,将立即返回结果,否则会阻塞当前线程,直到任务进入完成状态,然后返回结果或者抛出异常。
//所以要多线程同时运行,保存多个future的引用,待线程执行完成后再获取结果
List<Future<Integer>> list = new ArrayList<>();
for (int i = 0; i < 100; i++) {
Future<Integer> c = threadPool.submit(new Work());
list.add(c);
}
//shutdown执行完当前正在运行的线程和已经加入队列中的任务才会关闭线程池
threadPool.shutdown();
while (true) {
if (threadPool.isTerminated()) {
break;
}
}
System.out.println(list.size() + "==========");
for (Future<Integer> future : list) {
try {
System.out.println(future.get() + "--------------");
} catch (InterruptedException e) {
} catch (ExecutionException e) {
}
}
System.out.println("end=========" + String.valueOf(System.currentTimeMillis() - begin));
}
static class Work implements Callable<Integer> {
@Override
public Integer call() {
Random r = new Random();
try {
Thread.currentThread().sleep(1000);
System.out.println(Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
return r.nextInt(5000);
}
}
}
使用CompletionService解决方案:
public class TestShutdown2 {
public static ExecutorService threadPool = Executors.newFixedThreadPool(5);
public static void main(String[] args) {
try {
Long begin = System.currentTimeMillis();
CompletionService<Integer> ecs = new ExecutorCompletionService<Integer>(threadPool);
for (int i = 0; i < 100; i++) {
ecs.submit(new Work());
}
for (int i = 0; i < 100; ++i) {
Integer r = null;
try {
r = ecs.take().get();
} catch (InterruptedException e) {
} catch (ExecutionException e) {
}
if (r != null)
System.out.println(r);
}
System.out.println("end=========" + String.valueOf(System.currentTimeMillis() - begin));
} catch (Exception e) {
} finally {
threadPool.shutdown();
}
}
static class Work implements Callable<Integer> {
@Override
public Integer call() {
Random r = new Random();
try {
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return r.nextInt(5000);
}
}
}