10年前单核CPU电脑,假的多线程,像马戏团小丑玩多个球,CPU需要来回切换。
现在是多核电脑,多个线程各自跑在独立的CPU上,不用切换效率高。
线程池做的主要工作是控制运行的线程数量,处理过程中将任务放入队列,然后在线程创建后启动这些任务,如果线程数量超过了最大数量,那么超出数量的线程将排队等候,等其他线程执行完毕,再从队列中取出任务来执行。
1.3、线程池的主要特点线程复用、控制最大并发数、管理线程
第一:降低资源消耗。通过重复利用已创建的线程降低线程创建和销毁造成的销耗。
第二:提高响应速度。当任务到达时,任务可以不需要等待线程创建就能立即执行。
第三:提高线程的可管理性。线程是稀缺资源,如果无限制的创建,不仅会销耗系统资源,还会降低系统的稳定性,使用线程池可以进行统一的分配,调优和监控。
Java中的线程池是通过Executor框架实现的,该框架中用到了Executor,Executors,ExecutorService,ThreadPoolExecutor这几个类。
1.5.1、一池N线程的固定线程
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new linkedBlockingQueue());
}
1.5.2、一池一线程
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new linkedBlockingQueue()));
}
1.5.3、根据需要创建新线程(可扩容)
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue());
}
1.6、线程池案例
package com.atguigu.juc;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MyThreadPoolDemo {
public static void main(String[] args) {
//ExecutorService threadPool = Executors.newFixedThreadPool(5);//一个银行网点,5个受理业务的窗口
//ExecutorService threadPool = Executors.newSingleThreadExecutor();//一个银行网点,1个受理业务的窗口
ExecutorService threadPool = Executors.newCachedThreadPool();//一个银行网点,可扩展受理业务的窗口
//10个顾客请求
try {
for (int i = 1; i <= 10; i++) {
threadPool.execute(() -> {
System.out.println(Thread.currentThread().getName() + "t办理业务");
});
}
} catch (Exception e) {
e.printStackTrace();
} finally {
threadPool.shutdown();
}
}
}
1.7、ThreadPoolExecutor底层原理
1.8、线程池七大参数
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
if (corePoolSize < 0 ||
maximumPoolSize <= 0 ||
maximumPoolSize < corePoolSize ||
keepAliveTime < 0)
throw new IllegalArgumentException();
if (workQueue == null || threadFactory == null || handler == null)
throw new NullPointerException();
this.acc = System.getSecurityManager() == null ?
null :
AccessController.getContext();
this.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.workQueue = workQueue;
this.keepAliveTime = unit.toNanos(keepAliveTime);
this.threadFactory = threadFactory;
this.handler = handler;
}
1.9、线程池底层工作原理
(1)创建了线程池后,开始等待请求。
(2)当调用execute()方法添加一个请求任务时,线程池会做出如下判断:
a、如果正在运行的线程数量小于corePoolSize,那么马上创建线程运行这个任务;
b、如果正在运行的线程数量大于或者等于corePoolSize,那么将这个任务放入队列;
c、如果这个时候队列满了且正在运行的线程数量还小于maximumPoolSize,那么还是要创建非核心线程立刻运行这个任务;
d、如果队列满了且正在运行的线程数量大于或等于maximumPoolSize,那么线程池会启动饱和拒绝策略来执行。
(3) 当一个线程完成任务时,它会从队列中取下一个任务来执行。
(4) 当一个线程无事可做超过一定的时间(keepAliveTime)时,线程会判断:
a、如果当前运行的线程数大于corePoolSize,那么这个线程就被停掉。
b、所有线程池的所有任务完成后,它最终会收缩到corePoolSize的大小。



