线程使用上的问题
new Thread().start();
1、线程的频繁创建销毁比较浪费资源
2、线程的数量过多,会造成CPU资源的额外开销。(上下文切换消耗cpu资源)
思考: 如何实现线程的复用?
池化技术
举例: 连接池、对象池、内存池、线程池 。。。
池化技术的核心:复用
线程池
提前创建一系列的线程,保存在这个线程池中。
有任务要执行的时候,从线程池中取出线程来执行。
没有任务的时候,放回线程池。
Java中提供的线程池
Executors 线程池创建工厂类
创建线程池对象的方法:
- newFixedThreadPool 固定线程数量
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue());
}
- newSingleThreadExecutor 只有一个线程的线程池
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue()));
}
- newCachedThreadPool 可以缓存的线程池 ->理论上来说,有多少请求,该线程池就可以创建多少的线程来处理。
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue());
}
- newScheduledThreadPool 提供了按照周期执行的线程池. ->Timer
public static ScheduledExecutorService newScheduledThreadPool(int
corePoolSize) {
return new ScheduledThreadPoolExecutor(corePoolSize);
}
二、线程池设计猜想
需求:实现线程的重复使用.
分析:
如何实现线程的复用?
让线程实现复用的唯一的方法,就是让线程不结束。
那如何让线程执行新的任务呢?也就是说,任务怎么给它执行?
[共享内存]-> List.add()
线程一直处于运行状态,合理吗?
- 有任务来的时候,执行
- 没有任务的时候,阻塞
结论:通过阻塞队列的方式,来实现线程池中线程的复用。
线程池的实现原理的过程推演



