目录
一、线程池的优势:
线程做的工作只要控制运行的线程数量,处理过程中将任务放入队列,然后线程创建后启动这些任务,如果线程数量超过了最大数量,超出数量的线程排队等候,等其他线程执行完毕,再从队列中取出任务来执行。
它的主要特点为:
线程复用,控制最大并发数,管理线程。
优点:降低资源消耗,提高响应速度,提高线程的可管理性。
线程如何使用:
线程池:三大方法、7大参数、4种拒绝策略
线程池的好处:
1、降低资源的消耗
2、提高响应的速度
3、方便管理。
二、Executor框架
Java中的线程池是通过Executor框架来实现的,该框架中用到了,
接口:Executor,ExecutorService , ScheduledExecutorService
类:Executors,AbstractExecutorService ,ThreadPoolExecutor , ScheduledThreadPoolExecutor ,
Executor: 所有线程池的接口,只有一个方法。
ExecutorService: 增加Executor的行为,是Executor实现类的最直接接口。
Executors: 提供了一系列工厂方法用于创先线程池,返回的线程池都实现了ExecutorService 接口。
ThreadPoolExecutor:线程池的具体实现类,一般用的各种线程池都是基于这个类实现的。
三、Executors线程池的工具类
// Executors 工具类、3大方法
public class poolTest {
public static void main(String[] args) {
//单个线程
Executors.newSingleThreadExecutor();
//创建固定数量线程的线程池
Executors.newFixedThreadPool(5);
//可伸缩的线程池
ExecutorService threadPool = Executors.newCachedThreadPool();
try {
for (int i = 0; i < 100; i++) {
threadPool.execute(()->{
System.out.println(Thread.currentThread().getName()+"ok");
});
}
} catch (Exception e) {
e.printStackTrace();
} finally {
threadPool.shutdown();
}
}
}
四、ThreadPoolExecutor底层原理
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,//21亿多
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
//本质都是调用ThreadPoolExecutor
//最终会调用