阿里在规范中明确规定不使用jdk中的线程池,原因是jdk中线程池没有对队列大小规范,可能会造成java虚拟机内存异常。
在面试中中小公司也喜欢对自定义线程进行考核。我们尝试以简单的方式来讲解如何自定义线程池。
JDK常用线程池
以下列举出了JDK实现的线程池,虽然在项目中禁止使用,但是可以给我们提供良好的自定义线程实现案例。
Executors
- newSingleThreadExecutor
- newFixedThreadExecutor
- newCachedThreadPool
- newScheduledThreadPool
- 等
自定义线程
自定义线程池模型
![image-20230907095431190](https://i-blog.csdnimg.cn/blog_migrate/94927d693b48df09fcfe931e2c7235c5.png)
线程池常用七大参数
序列 | 参数名 | 含义 |
---|---|---|
1 | corePoolSize | 核心线程数 |
2 | maximumPoolSize | 最大线程数(必须大于核心线程数) |
3 | keepAliveTime | 空闲线程的存活时间 |
4 | Unit | 时间单位 |
5 | workQueue | 用于存放任务的队列 |
6 | threadFactory | 线程工厂、用来创建新线程 |
7 | handler | 处理别拒绝的任务 |
自定义线程池实现
int corePoolSize = 4;
int maximumPoolSize = 10;
long keepAliveTime= 10000;
TimeUnit unit = TimeUnit.MILLISECONDS;
BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(10);
ThreadFactory threadFactory=null;
RejectedExecutionHandler handler=null;
ThreadPoolExecutor myPool = new ThreadPoolExecutor(
corePoolSize,
maximumPoolSize,
keepAliveTime,
unit,
workQueue,
threadFactory,
handler
);
package com.wnhz.thread;
import java.util.concurrent.*;
public class CustomerThreadPool {
/**
* 定义线程池工厂,目的产生线程
*/
static class SimpleThreadFactory implements ThreadFactory {
public Thread newThread(Runnable r) {
return new Thread(r);
}
}
/**
* 定义拒绝策略
*/
static class MyAbortPolicy implements RejectedExecutionHandler {
/**
* Creates an {@code AbortPolicy}.
*/
public MyAbortPolicy() { }
/**
* Always throws RejectedExecutionException.
*
* @param r the runnable task requested to be executed
* @param e the executor attempting to execute this task
* @throws RejectedExecutionException always
*/
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
throw new RejectedExecutionException("任务 " + r.toString() +
" 拒绝 from " +
e.toString());
}
}
public static void main(String[] args) {
int corePoolSize = 4;
int maximumPoolSize = 10;
long keepAliveTime = 10000;
TimeUnit unit = TimeUnit.MILLISECONDS;
BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(10);
// ThreadFactory threadFactory = new ThreadFactory() {
// @Override
// public Thread newThread(Runnable r) {
// System.out.println("创建线程:"+r);
// return new Thread(r);
// }
// };
RejectedExecutionHandler handler = null;
ThreadPoolExecutor myPool = new ThreadPoolExecutor(
corePoolSize,
maximumPoolSize,
keepAliveTime,
unit,
workQueue,
r->{
System.out.println("创建线程:"+r);
return new Thread(r);
},
new MyAbortPolicy()
);
for (int t=0;t<20;t++) {
myPool.execute(()->{
for (int i=0;i<10;i++) {
System.out.println(Thread.currentThread().getName()+":"+i);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
}
}