1. 把线程提前创建好,放到池子里,后面需要用线程,就直接从池子里取,不必从系统这边申请,线程用完了,也不是还给系统,而是放回池子里,以备下次再使用,这就使创建销毁过程更加快速。
2. 为什么从线程池中调用要比从系统内申请释放资源更快?
3. java标准库的线程池
ThreadPoolExecutor
4. 简化版本的线程池
Executors 本质上是 ThreadPoolExecutor 类的封装.
线程池的几种创建方式:
1)创建出固定包含 若干个线程的线程池,返回值类型为 ExecutorService
ExecutorService pool = Executors.newFixedThreadPool(10);
2) 创建一个自动扩容的线程池,会根据任务量来进行自动扩容
Executors.newCachedThreadPool();
3)创建只包含单个线程的线程池
Executors.newSingleThreadExecutor();
4)设创建一个带有定时器功能的线程池,是进阶版的Timer
Executors.newScheduledThreadPool(1000);
5. 线程池的简单使用
public class Demo01 { public static void main(String[] args) { ExecutorService pool = Executors.newFixedThreadPool(10); //通过submit 可以注册一个任务到线程池中 pool.submit(new Runnable() { @Override public void run() { System.out.println("hello threadPool"); } }); } }