目录
RejectedExecutionHandler handler
一、线程池
(一)线程池是什么
最初从进程引出线程的时候,就是因为频繁地创建和销毁进程,是一个开销很大的事,
对于线程,如果频繁创建和开销消耗的资源依旧不小,所以引入了“线程池”的概念。
线程池,就是为了高效创建和销毁线程的
想象这么一个场景:
在学校附近新开了一家快递店,老板很精明,想到一个与众不同的办法来经营。店里没有雇人
,而是每次有业务来了,就现场找一名同学过来把快递送了,然后解雇同学。这个类比我们平时来一个任务,起一个线程进行处理的模式。
很快老板发现问题来了,每次招聘 + 解雇同学的成本还是非常高的。老板还是很善于变通的,知道了为什么大家都要雇人了,所以指定了一个指标,公司业务人员会扩张到 3 个人,但还是随着业务逐步雇人。于是再有业务来了,老板就看,如果现在公司还没 3 个人,就雇一个人去送递,否则只是把业务放到一个本本上,等着3 个快递人员空闲的时候去处理。这个就是我们要带出的线程池的模式。
线程池最大的好处就是减少每次启动、销毁线程的损耗。
(二)为什么认为,直接创建线程比从线程池中取线程开销更大呢
-
创建/销毁成本高
直接创建:每次需系统调用、分配栈内存,耗时(约毫秒级)。
-
线程池:线程复用,避免重复创建/销毁。
-
资源占用大
直接创建:每个线程独立占用内存(默认MB级栈空间),易耗尽资源。
-
线程池:固定线程数,控制总资源消耗。
-
上下文切换频繁
直接创建:线程过多导致CPU频繁切换,降低性能。
-
线程池:限制活跃线程数,减少切换开销。
-
任务调度效率低
直接创建:无任务队列,突发流量可能瞬间创建大量线程。
-
线程池:任务排队,按需扩展(避免线程爆炸)。
-
系统稳定性差
直接创建:可能触发系统线程数上限(如Linux的
pid_max)。 -
线程池:资源可控,避免崩溃。
(三)Java标准库中的线程池
1.ThreadPoolExecutor类
ThreadPoolExecutor 是 Java 并发包 (java.util.concurrent) 提供的线程池实现类
2.ThreadPoolExecutor中的核心方法
(1)submit方法
submit(runnable)是线程池中的核心方法
通过Runnable描述一段需要执行的任务,通过submit任务放到线程池中,此时线程池中的线程就会执行这样的任务。
Future<?> submit(Runnable task)
(2)构造方法
ThreadPoolExecutor中的构造方法有以下四种:

下面介绍完整参数的构造方法:
ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler)
(3)构造方法中的参数
int corePoolSize
表示核心线程数,线程池一创建,这些线程也随之创建,直到整个线程池销毁,这些线程才会销毁
int maximumPoolSize
表示最大线程数=核心线程数+非核心线程数(自适应的,繁忙就创建,不繁忙就销毁)
long keepAliveTime
表示非核心线程允许空闲的最大时间,空闲超过这个时间线程就销毁
TimeUnit unit
表示枚举,用于设置时间的类型
BlockingQueue<Runnable> workQueue
表示工作队列,是一个阻塞队列
线程池本质上也是一个生产者消费者模型,调用submit就是在生产任务,线程池中的线程就是在消费任务

ThreadFactory threadFactory
这是一个工厂模式,工厂模式也是一种设计模式,主要是用来弥补构造方法的缺陷的
构造方法的名字是固定的,想要提供不同的版本,就需要通过重载,有时候不一定能构成,所以有了工厂模式
class Point{
}
class PointFactory{
public static Point makePointByXy(int x,int y){
Point p=new Point();
//设置属性
return p;
}
public static Point makePointByRa(int r,int a){
Point p=new Point();
//设置属性
return p;
}
}
RejectedExecutionHandler handler
表示的是拒绝策略。
submit将任务添加到任务队列中,任务队列是阻塞队列
队列满了再添加就会阻塞,一般不希望程序会阻塞太久
对于线程池来说,发现入队列操作时,队列满了,不会真正触发“入队列”操作
不会真的阻塞,而是执行拒绝策略相关的代码
有四种拒绝策略:

3.Executors类
Java标准库也提供了另一种针对ThreadPoolExecutor类进行了进一步封装的类,来简化线程池的使用
使用 Executors.newFixedThreadPool(10) 能创建出固定包含 10 个线程的线程池.
• 返回值类型为 ExecutorService
• 通过 ExecutorService.submit 可以注册一个任务到线程池中.
Executors 创建线程池的几种方式:
• newFixedThreadPool: 创建固定线程数的线程池
• newCachedThreadPool: 创建线程数目动态增长的线程池
• newSingleThreadExecutor: 创建只包含单个线程的线程池
• newScheduledThreadPool: 设定延迟时间后执行命令,或者定期执行命令,是进阶版的 Timer
(四)自己实现一个固定线程个数的线程池


代码实现如下:
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
//实现线程池
class MyThreadPoll{
//创建阻塞队列
BlockingQueue<Runnable> queue=new LinkedBlockingQueue(1000);
//构造方法
public MyThreadPoll(int n){
for(int i=0;i<n;i++){
Thread t=new Thread(()->{
try {
//别忘了是while
while(true){
Runnable task = queue.take();//从队列中出一个可执行任务
task.run();
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
//别忘了启动线程
t.start();
}
}
//submit方法
public void submit(Runnable task) throws InterruptedException {
// 将任务放入队列中
queue.put(task);
}
}
public class Demo27 {
public static void main(String[] args) throws InterruptedException {
MyThreadPoll pool=new MyThreadPoll(10);
for(int i=0;i<1000;i++){
int id=i;
pool.submit(()->{
System.out.println("当前执行的线程:"+Thread.currentThread().getName()+" "+"id:"+id);
});
}
}
}
二、定时器
定时器是一种实际开发中非常常用的组件.比如网络通信中,如果对方 500ms 内没有返回数据,则断开连接尝试重连.
比如一个 Map, 希望里面的某个 key 在 3s 之后过期(自动删除).
类似于这样的场景就需要用到定时器.
(一)标准库中的定时器
标准库中提供了一个Timer类,Timer 类的核心方法为 schedule。
schedule 包含两个参数。第一个参数指定即将要执行的任务代码,第二个参数指定多长时间之后执行
在标准库中,
Timer.schedule()方法的第一个参数通常是TimerTask类型的对象,因为TimerTask是一个抽象类,封装了要执行的任务逻辑(通过重写其run()方法)。这是 Java 标准库的实现方式。
import java.util.Timer;
import java.util.TimerTask;
//标准库中的定时器
public class Demo28 {
public static void main(String[] args) {
Timer timer=new Timer();
timer.schedule(new TimerTask() {//匿名内部类
@Override
public void run() {
System.out.println("hello timer");
}
},3000);
}
}
(二)自己实现定时器

package Thread;
import java.util.PriorityQueue;
class MyTimerTask implements Comparable<MyTimerTask>{
private Runnable task;
private long time;
public MyTimerTask(Runnable task,long time){
this.task=task;
this.time=time;
}
public int compareTo(MyTimerTask o){
return (int)(this.time-o.time);
}
public long getTime(){
return this.time;
}
public void run(){
task.run();
}
}
class MyTimer{
//创建一个锁
public Object locker=new Object();
///创建一个优先级队列
private PriorityQueue<MyTimerTask> queue=new PriorityQueue<>();
public MyTimer(){
Thread t=new Thread(()->{
//从队列中拿出元素,并执行
try {
while (true) {
synchronized (locker) {
//先判断队列是否为空
if (queue.isEmpty()) {
//这里阻塞,等待schedule唤醒
locker.wait();
}
MyTimerTask task = queue.peek();
//是peek而不是poll,因为还没有判断时间到没有
if (System.currentTimeMillis() < task.getTime()) {
//如果当前任务规定的时间大于系统的计时,说明时间还没到
//阻塞等待
locker.wait(task.getTime() - System.currentTimeMillis());
} else {
//到时间了,执行
task.run();
//出队列
queue.poll();
}
}
}
}catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
t.start();
}
public void schedule(Runnable runnable,long dalay){
synchronized(locker){
MyTimerTask task=new MyTimerTask(runnable,System.currentTimeMillis()+dalay);
//System.currentTimeMillis():获取当前时间戳
queue.offer(task);
locker.notify();
}
}
}
public class Demo29 {
public static void main(String[] args) {
MyTimer timer=new MyTimer();
timer.schedule(()->{
System.out.println("hello 3000");
},3000);
timer.schedule(()->{
System.out.println("hello 2000");
},2000);
timer.schedule(()->{
System.out.println("hello 1000");
},1000);
}
}

1351




被折叠的 条评论
为什么被折叠?



