池化技术:事先准备好一些资源,有人要用,就来我这里拿,用完之后还给我
程序的运行的本质 :占用系统的资源! 池化技术可以优化资源的使用
线程池、连接池、内存池、对象池///......创建、销毁十分浪费资源
线程池的好处:
① 降低资源的消耗
② 提高响应的速度
③ 方便管理
线程池的作用:线程复用、可以控制最大并发数、管理线程
三大方法
① newSingleThreadExecutor()
ExecutorService threadPool = Executors.newSingleThreadExecutor();
创建单个线程,可以想象成大小为1的线程池,只有一个线程能执行
public static void main(String[] args) {
ExecutorService threadPool = Executors.newSingleThreadExecutor(); // 单个线程
try {
for (int i = 1; i <= 10; i++) {
// 创建线程池后用线程池来创建线程
threadPool.execute(()->{
System.out.println(Thread.currentThread().getName());
});
}
}finally {
threadPool.shutdown(); // 关闭线程池,线程池用完程序结束必须关闭线程池
}
}
运行结果:
pool-1-thread-1
pool-1-thread-1
pool-1-thread-1
pool-1-thread-1
pool-1-thread-1
pool-1-thread-1
pool-1-thread-1
pool-1-thread-1
pool-1-thread-1
pool-1-thread-1
线程复用,10个任务被同一个线程执行
② newFixedThreadPool(int nThreads)
ExecutorService threadPool = Executors.newFixedThreadPool(5);
创建一个固定大小的线程池,最多允许 nThreads 个线程同时执行