package com.lyon.juc.pool;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPoolDemo {
public static void main(String[] args) {
//不建议使用Executors去创建线程池,因为最大线程数是默认的Integer.MAX_VALUE 2的31次方-1(可能导致内存溢出)
//ExecutorService executorService = Executors.newSingleThreadExecutor();//单个线程
//ExecutorService executorService = Executors.newFixedThreadPool(5);//固定大小的线程池
ExecutorService executorService = Executors.newCachedThreadPool();//可伸缩的
try {
for (int i = 0; i < 100; i++) {
executorService.execute(()->{
System.out.println(Thread.currentThread().getName());
});
}
}catch (Exception e) {
e.printStackTrace();
}finally {
//线程池,使用完,要关闭
executorService.shutdown();
}
}
}
|