- 线程池的参数介绍
- 线程池的工作流程
- 使用Executors 创建常见的线程池
1.线程池的参数介绍
int corePoolsSize | 最大核心线程数 |
int maximumPoolSize | 最大线程数(核心线程数+非核心线程数) |
long keepAliveTime | 非核心线程允许存在的最大空闲时间 |
TimeUnit unit | keepALiveTime的时间单位,时分秒之类 |
BlockingQueue<Runnable> workQueue | 要执行的任务线程队列 |
ThreadFactory threadFactory | 创建线程的工厂类,使用不同的工厂相当于对线程池进行不同的初始化 |
RejectedExecutionHandler | 拒绝策略 |
线程池的拒绝策略(核心参数)
AbortPolicy()直接抛出异常:当线程池满了,还要继续添加任务就直接抛出异常
CallerRunsPolicy()由调用者负责执行:当队列满了,在submit提交任务的时候就直接调用Runnable的run()方法
DiscardOldestPolicy()直接舍弃最老的任务:直接抛弃队头的任务
DiscardPolicy()直接舍弃最新的任务:直接抛弃当前要入队列的任务
2.线程池的工作介绍
线程池在创建的时候会规定有多少核心线程和最大线程数,最大线程数=核心线程+非核心线程,核心线程就相当于正式员工,非核心线程就相当于临时工,正式员工会一直存在,而临时工就是在队列中任务太多的时候,正式员工处理不过来的时候创建的,我们也会规定非核心线程的存活时间,这个存活时间指的是空闲的存活时间,如果一直没有任务由这个非核心线程执行,这个非核心线程就会被回收销毁;
我们还会有一个阻塞队列用来存放线程要执行的任务,Runnable,线程执行任务的一种接口;
实现线程池
核心操作是submit(),将任务提交到线程池中
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class MyThreadPool {
//创建一个阻塞队列用来存放线程池要执行的任务
BlockingQueue<Runnable> queue=new ArrayBlockingQueue<>(1000);
private int maxThread;
// n表⽰线程池⾥有⼏个线程
//创建了⼀个固定数量的线程池
public MyThreadPool(int maxThread){
this.maxThread=maxThread;
for (int i = 0; i < maxThread; i++) {
Thread t=new Thread(){
@Override
public void run() {
try{
while(true){
Runnable runnable=queue.take();
runnable.run();
}
}catch(InterruptedException e){
e.printStackTrace();
}
}
};
t.start();
}
}
public void submit(Runnable runnable) throws InterruptedException {
queue.put(runnable);
}
}
public class test {
public static void main(String[] args) throws InterruptedException {
MyThreadPool myThreadPool=new MyThreadPool(4);
for (int i = 0; i < 1000; i++) {
int id=i;
myThreadPool.submit(new Runnable() {
@Override
public void run() {
System.out.println(id+Thread.currentThread().getName()+"hello");
}
});
}
}
}
3.使用Executors 创建常见的线程池
java标准库给我们提供了四种方便的创建线程池的方法
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class demo1 {
public static void main(String[] args) {
//创建一个没有上限个数线程的线程池,当没有空闲线程来执行任务了,就会创建新的线程
Executors.newCachedThreadPool();
//创建一个只有一个线程的线程池,保证任务按顺序执行
Executors.newSingleThreadExecutor();
//创建一个固定线程个数的线程池,支持延时执行的
Executors.newScheduledThreadPool(10);
//创建一个固定线程个数的线程池
ExecutorService service=Executors.newFixedThreadPool(10);
for (int i = 0; i < 1000; i++) {
int id=i;
service.submit(new Runnable() {
@Override
public void run() {
System.out.println(id+Thread.currentThread().getName()+"hello");
}
});
}
}
}