Java多线程(ExecutorService), 等待所有线程执行完毕.
常用的两种方式:
-
ExecutorService taskExecutor = Executors.newFixedThreadPool(4);
-
while(...) {
-
taskExecutor.execute(new MyTask());
-
}
-
taskExecutor.shutdown();
-
try {
-
taskExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
-
} catch (InterruptedException e) {
-
...
-
}
-
CountDownLatch latch = new CountDownLatch(totalNumberOfTasks);
-
ExecutorService taskExecutor = Executors.newFixedThreadPool(4);
-
while(...) {
-
taskExecutor.execute(new MyTask());
-
}
-
-
try {
-
latch.await();
-
} catch (InterruptedException E) {
-
// handle
-
}
然后在线程方法中加入:
-
try {
-
...
-
} catch (Exception e) {
-
e.printStackTrace();
-
}finally {
-
countDownLatch.countDown();
-
}