前言
今日让老师给我优化简历,他说我项目很像培训机构出来的。不属于学生时代就能做出来的作品。
学习别人优秀项目,明天去深挖那个项目。
1.深挖线程池源码
昨天挖了他提交任务的源码,任务提交。大概流程如下
当然还有很多操作没有弄,比如他会判断当前线程池状态如果已经结束了也会调用拒绝策略,等细节。
还有一个也是我找源码很久的疑问就是这个工作线程他一直是new好像并没有把他复用啊,到底是哪里复用了。 以下给出哪里复用代码
final void runWorker(Worker w) {
Thread wt = Thread.currentThread();
Runnable task = w.firstTask;
w.firstTask = null;
w.unlock(); // allow interrupts
boolean completedAbruptly = true;
try {
//线程复用在这里 task = getTask()
while (task != null || (task = getTask()) != null) {
w.lock();
// If pool is stopping, ensure thread is interrupted;
// if not, ensure thread is not interrupted. This
// requires a recheck in second case to deal with
// shutdownNow race while clearing interrupt
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);
}
}
这里哪里进行线程复用了呢
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))
//这里返回空 外面的while循环就结束了 然后他的finally方法里面会把他remove掉
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;
}
}
}
可见线程复用就这这里,被创建出来的工作线程不会停歇一直在等待有任务入队然后换行,这里是通过阻塞队列实习线程阻塞,用的是ReentrantLock的条件队列来实现线程的阻塞和唤醒的。之后有时间给大家