Executors.newCachedThreadPool();
无限制创建线程。
package com.itcast.thread;
import java.time.LocalDateTime;
import java.util.PrimitiveIterator;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @Description
* @Author by mocar小师兄
* @Date 2019/11/29 12:22
**/
public class NewCachedThreadPool {
public static void main(String[] args) {
ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
for (int index = 0; index <5 ; index++) {
//final int index=num;
System.out.println("循环:" + index + "开始");
cachedThreadPool.execute(() -> {
LocalDateTime startTime = LocalDateTime.now();
System.out.println(Thread.currentThread().getName() + "......开始执行");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "......执行完成");
LocalDateTime endTime = LocalDateTime.now();
System.out.println(Thread.currentThread().getName() +",耗时:" + (endTime.getSecond()-startTime.getSecond()));
});
System.out.println("循环:" + index + "结束");
}
cachedThreadPool.shutdown();
System.out.println("thread main 结束");
}
}