java官方提供了一个Executors来帮助我们创建线程池 但是不推荐 因为这样对线程的控制粒度比较低 我们只能传入创建的线程数量 并不能知道线程的名字和很多东西 推荐手动创建线程池
创建线程池的各种参数:
public ThreadPoolExecutor(int corePoolSize, 核心线程数
int maximumPoolSize, 最大线程数
long keepAliveTime, 最大空闲时间
TimeUnit unit, 时间单位
BlockingQueue<Runnable> workQueue, 阻塞队列
ThreadFactory threadFactory, 线程工厂 主要可以指定创建工厂的名字
RejectedExecutionHandler handler) 拒绝策略
线程池中的核心属性:
private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0)); 这个是一个状态位标志我们的线程池状态
高三位代表状态 低29位代表线程池的数量 这个AtomicInteger就是int类型 但是它对int类型修改时做了CAS操作
private static final int COUNT_BITS = Integer.SIZE - 3; 这个数就是29 因为int类型是32位的
private static final int CAPACITY = (1 << COUNT_BITS) - 1; 其实就是前三位是0 后29位全是1
private static final int RUNNING = -1 << COUNT_BITS; 正在运行状态 前三位 111
private static final int SHUTDOWN = 0 << COUNT_BITS; 表示shutdown状态 前三位000 不接收新线程 但是会处理阻塞队列中的任务 对正在执行的任务也正常处理
private static final int STOP = 1 << COUNT_BITS; 前三位是001 不接收新线程 也不去处理阻塞队列中的任务 同时会中断正在执行的任务
private static final int TIDYING = 2 << COUNT_BITS; 010 表示线程池是一个即将要销毁的中间态
private static final int TERMINATED = 3 << COUNT_BITS; 011 表示线程池已经销毁
private static int runStateOf(int c) { return c & ~CAPACITY; } 得到线程池当前的状态信息
private static int workerCountOf(int c) { return c & CAPACITY; } 得到当前线程池的线程数量
线程池的执行流程:
线程池的状态变化:
线程池的execute方法:
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
int c = ctl.get();
if (workerCountOf(c) < corePoolSize) {
if (addWorker(command, true))
return;
c = ctl.get();
}
if (isRunning(c) && workQueue.offer(command)) {
int recheck = ctl.get();
if (! isRunning(recheck) && remove(command))
reject(command);
else if (workerCountOf(recheck) == 0)
addWorker(null, false);
}
else if (!addWorker(command, false))
reject(command);
}
接下来我们来看一看添加工作线程是如何执行的:
private boolean addWorker(Runnable firstTask, boolean core) {
retry:
for (;;) {
int c = ctl.get();
int rs = runStateOf(c);
if (rs >= SHUTDOWN &&
! (rs == SHUTDOWN &&
firstTask == null &&
! workQueue.isEmpty()))
return false;
for (;;) {
int wc = workerCountOf(c);
if (wc >= CAPACITY ||
wc >= (core ? corePoolSize : maximumPoolSize))
return false;
if (compareAndIncrementWorkerCount(c))
break retry;
c = ctl.get();
if (runStateOf(c) != rs)
continue retry;
}
}
boolean workerStarted = false;
boolean workerAdded = false;
Worker w = null;
try {
w = new Worker(firstTask);
final Thread t = w.thread;
if (t != null) {
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
int rs = runStateOf(ctl.get());
if (rs < SHUTDOWN ||
(rs == SHUTDOWN && firstTask == null)) {
if (t.isAlive())
throw new IllegalThreadStateException();
workers.add(w);
int s = workers.size();
if (s > largestPoolSize)
largestPoolSize = s;
workerAdded = true;
}
} finally {
mainLock.unlock();
}
if (workerAdded) {
t.start();
workerStarted = true;
}
}
} finally {
if (! workerStarted)
addWorkerFailed(w);
}
return workerStarted;
}
我们再看一看Worker对象是如何封装的:
Worker(Runnable firstTask) {
setState(-1);
this.firstTask = firstTask;
this.thread = getThreadFactory().newThread(this);
}
我们看一看run方法,观察一下线程调用了start方法过后的流程:
调用runWorker方法 将自己作为参数传入:
final void runWorker(Worker w) {
Thread wt = Thread.currentThread();
Runnable task = w.firstTask;
w.firstTask = null;
w.unlock();
boolean completedAbruptly = true;
try {
while (task != null || (task = getTask()) != null) {
w.lock();
if ((runStateAtLeast(ctl.get(), STOP) ||
(Thread.interrupted() &&
runStateAtLeast(ctl.get(), STOP))) &&
!wt.isInterrupted())
wt.interrupt();
try {
beforeExecute(wt, task);
Throwable thrown = null;
try {
task.run();
} catch (RuntimeException x) {
thrown = x; throw x;
} catch (Error x) {
thrown = x; throw x;
} catch (Throwable x) {
thrown = x; throw new Error(x);
} finally {
afterExecute(task, thrown);
}
} finally {
task = null;
w.completedTasks++;
w.unlock();
}
}
completedAbruptly = false;
} finally {
processWorkerExit(w, completedAbruptly);
}
}
下面再展示一下如何实现beforeExecute和afterExecute其实很简单:
private static class MyThreadPool extends ThreadPoolExecutor{
public MyThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
}
public MyThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory);
}
public MyThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, handler);
}
public MyThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
}
@Override
protected void beforeExecute(Thread t, Runnable r) {
System.out.println("执行任务前的操作");
}
@Override
protected void afterExecute(Runnable r, Throwable t) {
System.out.println("执行任务后的操作");
}
}
public static void main(String[] args) {
ThreadPoolExecutor threadPoolExecutor = new MyThreadPool(2,
4,
10,
TimeUnit.MILLISECONDS,
new PriorityBlockingQueue<>(2),
new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
return thread;
}
}, new ThreadPoolExecutor.AbortPolicy());
threadPoolExecutor.execute(()->{
for (int i=0;i<2;i++){
System.out.println(-1 << 29);
}
});
}
执行结果:
|