代码如下
public static void multiThread(List<Integer> list) throws InterruptedException {
ExecutorService pool = Executors.newFixedThreadPool(list.size());
CountDownLatch countDownLatch = new CountDownLatch(list.size());//线程等待参数,等待次数为集合数量
list.stream().<Runnable>map(s -> () -> {
try {
Thread.sleep(1000);
System.out.println(s + "||||" + Thread.currentThread().getName());
} catch (Exception e) {
e.printStackTrace();
} finally {
countDownLatch.countDown();//每执行完一个线程,等待计数器减一
}
}).forEach(pool::execute);
countDownLatch.await();//当所有线程都工作完毕时,再进行下一步
pool.shutdown();
}
public static void main(String[] args) throws InterruptedException {
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
while (true) {
multiThread(list);
}
}
打印出来的东西如下:
5||||pool-1-thread-5
1||||pool-1-thread-1
3||||pool-1-thread-3
4||||pool-1-thread-4
2||||pool-1-thread-2
1||||pool-2-thread-1
2||||pool-2-thread-2
3||||pool-2-thread-3
5||||pool-2-thread-5
4||||pool-2-thread-4
1||||pool-3-thread-1
2||||pool-3-thread-2
3||||pool-3-thread-3
4||||pool-3-thread-4
5||||pool-3-thread-5
5||||pool-4-thread-5
2||||pool-4-thread-2
4||||pool-4-thread-4
3||||pool-4-thread-3
1||||pool-4-thread-1
1||||pool-5-thread-1
5||||pool-5-thread-5
4||||pool-5-thread-4
2||||pool-5-thread-2
3||||pool-5-thread-3
可以看出pool-后面的线程池序号是在不断增长的,即使执行了shutdown()方法,这个对于实际的程序运行会不会有什么坏的影响?如何让线程池数量不变呢?框架为springboot