常用的两种方式:
第一种方式:来自大神cletus的回答, 原文链接
-
ExecutorService taskExecutor = Executors.newFixedThreadPool(4);
-
-
taskExecutor.execute(new MyTask());
-
-
-
-
taskExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
-
} catch (InterruptedException e) {
-
-
第二种方式:来自大神ChssPly76的回答, 原文链接
-
CountDownLatch latch = new CountDownLatch(totalNumberOfTasks);
-
ExecutorService taskExecutor = Executors.newFixedThreadPool(4);
-
-
taskExecutor.execute(new MyTask());
-
-
-
-
-
} catch (InterruptedException E) {
-
-
然后在线程方法中加入:
-
-
-
-
-
-
countDownLatch.countDown();
-
Java多线程(ExecutorService), 等待所有线程执行完毕.
原文:https://www.cnblogs.com/telwanggs/p/13979612.html