作用
CPU的线程是稀有资源,创建和销毁需要成本较高,故在需要反复用到同一个线程的时候是可以使用线程池的
自定义线程池
package wen.ching.learn.base.multithread;
import org.junit.Test;
import java.util.HashSet;
import java.util.concurrent.*;
/**
* @author Wen_ching on 2018/6/15.
*/
public class Pool {
@Test
public void teste() {
ExecutorService pool = Executors.newCachedThreadPool();
Future<?> submit = pool.submit(() -> {
});
pool.execute(() -> {
});
}
@Test
public void futureTimeOutTest() {
System.out.println("main start");
FutureTask<String> futureTask = new FutureTask<>(() -> {
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "111";
});
ExecutorService pool = Executors.newCachedThreadPool();
pool.submit(futureTask);
try {
System.out.println("thread get " + futureTask.get(3, TimeUnit.SECONDS));
//主线程会阻塞 直到获取到值
System.out.println("main over");
} catch (Exception e) {
e.printStackTrace();
}
pool.shutdown();
}
/**
* 模拟ThreadPoolExecutor基本功能
*/
static class MyThreadPoolV2 {
private final int queueMax = 10;//有界缓存队列大小 一般使用的无界队列
//新建ThreadPoolExcutor需要一般需要如下参数 THreadFactory忽略
private volatile int corePoolSize = 3;//核心线程数
private volatile int maximumPoolSize = 8;//最大线程数
private volatile RejectedExecutionHandler rejectHandle = new ThreadPoolExecutor.AbortPolicy();//拒绝策略 默认抛异常
private volatile BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(queueMax);//缓存队列
private volatile long keepAliveTime;//线程存活设置
private volatile TimeUnit unit;//线程存活设置
// private ThreadPoolExecutor threadPool = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, rejectHandle);
private volatile boolean isShutDown =false;//打开、关闭线程池
public MyThreadPoolV2() {
}
public MyThreadPoolV2(int corePoolSize, int maximumPoolSize, RejectedExecutionHandler rejectHandle, BlockingQueue<Runnable> workQueue, TimeUnit unit, long keepAliveTime) {
this.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.rejectHandle = rejectHandle;
this.workQueue = workQueue;
this.unit = unit;
this.keepAliveTime = keepAliveTime;
}
//工作线程池 final修饰仅可被赋值一次 即地址不会变 但地址指向的内容可变
private final HashSet<Thread> workerPool = new HashSet<>();
public void execute(Runnable task){
if(task==null) throw new NullPointerException();
int workNum= workerPool.size();
//已有工作线程小于核心线程数 则直接创造新线程执行
if(workerPool.size() < corePoolSize){
Worker worker=new Worker(task);
Thread thread = new Thread(worker);
System.out.println("开启核心线程执行新任务"+thread.getName()+"任务:" +task);
workerPool.add(thread);//新创建的线程放入线程池中
thread.start();
} else if(workQueue.size()<10){//任务池还没满,就把任务放进任务池里
System.out.println("核心线程已全部开启 新任务放入缓存队列"+task);
workQueue.add(task);
}
else if(workNum<maximumPoolSize && workQueue.size()>=10){//任务队列满,开启多余线程来完成任务
Worker worker=new Worker(task);
Thread thread=new Thread(worker);
System.out.println("缓存满了之后还有新任务则开启新线程至最大线程数并执行"+thread.getName()+"任务:" +task);
workerPool.add(thread);
thread.start();
}
else{
System.out.println("拒绝执行,策略为放弃该任务什么也不做 或者抛异常等,任务" + task);
return;
}
}
public void shutdown(){
this.isShutDown = true;
for (Thread worker:
workerPool) {
System.out.println("终止工作线程名:" + worker.getName());
worker.interrupt();
}
System.out.println("终止线程池线程.");
Thread.currentThread().interrupt();
}
private class Worker implements Runnable{//任务包装类
private Runnable task_origal;
public Worker() {
}
public Worker(Runnable task) {
this.task_origal=task;
}
@Override
public void run() {
if(task_origal!=null)
task_origal.run();
while(!isShutDown){
try {
//每个线程启动后会不断的去任务列表中去任务 线程自旋则不会被销毁
Runnable task=workQueue.take();//阻塞提取任务,阻塞状态下的中断并不会真的中断
task.run();
} catch (InterruptedException e) {//这个异常是BlockingQueue的
// e.printStackTrace();
System.out.println("真的终止了");
Thread.currentThread().interrupt();
}
}
}
}
}
@Test
public void MyThreadPoolV2Test() throws InterruptedException {
MyThreadPoolV2 pool = new MyThreadPoolV2();
for(int i= 0; i<20;i++){
int finalI = i;
pool.execute(new Runnable() {
@Override
public void run() {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ":" + finalI);
}
@Override
public String toString() {
return "runable task:" + finalI;
}
});
}
TimeUnit.SECONDS.sleep(5);
pool.shutdown();
}
}
开启核心线程执行新任务Thread-0任务:runable task:0
开启核心线程执行新任务Thread-1任务:runable task:1
开启核心线程执行新任务Thread-2任务:runable task:2
核心线程已全部开启 新任务放入缓存队列runable task:3
核心线程已全部开启 新任务放入缓存队列runable task:4
核心线程已全部开启 新任务放入缓存队列runable task:5
核心线程已全部开启 新任务放入缓存队列runable task:6
核心线程已全部开启 新任务放入缓存队列runable task:7
核心线程已全部开启 新任务放入缓存队列runable task:8
核心线程已全部开启 新任务放入缓存队列runable task:9
核心线程已全部开启 新任务放入缓存队列runable task:10
核心线程已全部开启 新任务放入缓存队列runable task:11
核心线程已全部开启 新任务放入缓存队列runable task:12
缓存满了之后还有新任务则开启新线程至最大线程数并执行Thread-3任务:runable task:13
缓存满了之后还有新任务则开启新线程至最大线程数并执行Thread-4任务:runable task:14
缓存满了之后还有新任务则开启新线程至最大线程数并执行Thread-5任务:runable task:15
缓存满了之后还有新任务则开启新线程至最大线程数并执行Thread-6任务:runable task:16
缓存满了之后还有新任务则开启新线程至最大线程数并执行Thread-7任务:runable task:17
拒绝执行,策略为放弃该任务什么也不做 或者抛异常等,任务runable task:18
拒绝执行,策略为放弃该任务什么也不做 或者抛异常等,任务runable task:19
Thread-2:2
Thread-0:0
Thread-4:14
Thread-6:16
Thread-1:1
Thread-3:13
Thread-7:17
Thread-5:15
Thread-7:9
Thread-5:10
Thread-0:4
Thread-2:3
Thread-1:7
Thread-4:5
Thread-3:8
Thread-6:6
Thread-5:12
Thread-7:11
终止工作线程名:Thread-6
终止工作线程名:Thread-4
终止工作线程名:Thread-1
终止工作线程名:Thread-7
终止工作线程名:Thread-2
终止工作线程名:Thread-3
真的终止了
真的终止了
真的终止了
真的终止了
真的终止了
真的终止了
终止工作线程名:Thread-0
终止工作线程名:Thread-5
真的终止了
真的终止了
终止线程池线程.
原理总结
新任务放入线程封装类WorkerList 每个线程启动后会死循环的去workerlist中取任务 线程自旋则不会被销毁 则这个线程就可以一直使用 直到shutdown
其他在注解或打印信息中都写的很清楚,
至于空闲存活设置
//线程空闲存活时间 根据workQueue的poll方法来实现 如果队列为空 则等待时间后再去获
Runnable task=workQueue.poll(keepAliveTime,unit);//阻塞提取任务,阻塞状态下的中断并不会真的中断
if(task != null){
task.run();
}else{
System.out.println(Thread.currentThread().getName()+"等待空闲线程超时 关闭该线程");
Thread.currentThread().interrupt();
}
ThreadPoolExecutor & Executors
ThreadPoolExecutor用于创建线程池
而Executors是线程池的工具类,提供了多种常见应用场景的线程池实例,创建线程池一般使用工具类则可
比如缓存线程池
//缓存线程池 有任务则直接新建线程
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
//单线程池
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
//固定线程数量
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
再看下ThreedPoolExector封装的worker类
继承了AQS和runnable 功能上核心是run方法 而run方法核心调用的是如下getTask
private Runnable getTask() {
boolean timedOut = false; // Did the last poll() time out?
for (;;) {
int c = ctl.get();
int rs = runStateOf(c);
// Check if queue empty only if necessary.
if (rs >= SHUTDOWN && (rs >= STOP || workQueue.isEmpty())) {
decrementWorkerCount();
return null;
}
int wc = workerCountOf(c);
// Are workers subject to culling?
boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;
if ((wc > maximumPoolSize || (timed && timedOut))
&& (wc > 1 || workQueue.isEmpty())) {
if (compareAndDecrementWorkerCount(c))
return null;
continue;
}
try {
Runnable r = timed ?
workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
workQueue.take();
if (r != null)
return r;
timedOut = true;
} catch (InterruptedException retry) {
timedOut = false;
}
}
}