java线程池的执⾏顺序
//  thread.java
private Runnable target;//targets是runnable接⼝
//当thread.start()⽅法调⽤后,jvm会启动线程并调⽤run⽅法---target(runnable)调⽤run⽅法---
public void run(){
if(target != null){
target.run();//注意这⾥,⽆论是线程池的线程还是其他地⽅的,在start⽅法后,jvm都会执⾏这⾥的run⽅法,⽽target在那些地⽅已经被重写了,因此这⾥调⽤的run是我们程序员重写后定义的run⽅法,即执⾏任务。
}
}
线程池运⾏顺序:
execute(runnable任务a)-----
addworker:(塞进任务a)、a塞进worker,并通过work的线程成员来start开启线程
回看worker:
worker的构造⽅法:worker塞进a,并new⼀个线程,并将这个worker(它本⾝也是个runnable)塞进这个线程替换线程的runnable⽅法。注意:不是将a塞进去,⽽是将a封装进同样是runnable的worker中。
因此new的这个线程在addworker中start了,因此jvm会调⽤这个thread中的run⽅法,即重写的runnable的run⽅法,即worker的run⽅法;⽽worker的run⽅法—runWorker(this);此⽅法将a取出来并run起来。注意,重写的runnable接⼝,⾥⾯的⽅法体就是run⽅法。
/*
创建线程池的时候,实际上还没有创建线程,只是弄了⼀个框架,在执⾏到下⾯这段的时候才开创建。
创建线程池之后,进⼊
System.out.println(Thread.currentThread().getName()+" ok");
});
后⼜发⽣了什么,之后线程有没有被创建,以及在哪⾥被创建了。
*/
public class Demo01 {
public static void main(String[] args){
// ⾃定义线程池!⼯作 ThreadPoolExecutor
ExecutorService threadPool = new ThreadPoolExecutor(
2,
5,
3,
TimeUnit.SECONDS,
new LinkedBlockingDeque<>(3),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.DiscardOldestPolicy());//队列满了,尝试去和
最早的竞争,也不会抛出异常!
try {
// 最⼤承载:Deque + max
// 超过 RejectedExecutionException
for(int i =1; i <=9; i++){
// 使⽤了线程池之后,使⽤线程池来创建线程
System.out.println(Thread.currentThread().getName()+" ok");
});
}
} catch (Exception e){
e.printStackTrace();
} finally {
// 线程池⽤完,程序结束,关闭线程池
threadPool.shutdown();
}
}
}
//execute调⽤addworker进⼊创建线程的流程public void execute(Runnable command){ if(workerCountOf(c)< corePoolSize){
if(addWorker(command, true))
return;
c = ();
}
private boolean addWorker(Runnable firstTask, boolean core){
retry:
for(int c = ();;){
// Check if queue empty only if necessary.
if(runStateAtLeast(c, SHUTDOWN)
&&(runStateAtLeast(c, STOP)
|| firstTask != null
|| workQueue.isEmpty()))
return false;
for(;;){
if(workerCountOf(c)
>=((core ? corePoolSize : maximumPoolSize)& COUNT_MASK))
return false;
if(compareAndIncrementWorkerCount(c))
break retry;
c = ();// Re-rea
d ctl
if(runStateAtLeast(c, SHUTDOWN))
continue retry;
// else CAS failed due to workerCount change; retry inner loop
}
}
boolean workerStarted = false;
boolean workerAdded = false;
Worker w = null;
try {
w = new Worker(firstTask);//这⾥的firstTask指的是execute中的我们写的runnable⽅法,此时将它塞进worker⾥(注意这个work也是runnable⽅法)
final Thread t = w.thread;//t线程,那么jvm启动之后,运⾏t.run⽅法时,就是运⾏的我们重写了t的runnable⽅法,因此我们来t的runnable⽅法在哪⾥重写并塞进去的。⽽t来⾃于worker,那⾃然是worker⾥⾯必然已经塞了。
if(t != null){
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
// Recheck while holding lock.
// Back out on ThreadFactory failure or if
// shut down before lock acquired.
int c = ();
if(isRunning(c)||
java线程池创建的四种(runStateLessThan(c, STOP)&& firstTask == null)){
State()!= Thread.State.NEW)
throw new IllegalThreadStateException();
workers.add(w);
workerAdded = true;
int s = workers.size();
if(s > largestPoolSize)
largestPoolSize = s;
}
} finally {
mainLock.unlock();
}
if(workerAdded){
t.start();//开启线程
workerStarted = true;
}
}
} finally {
if(! workerStarted)
addWorkerFailed(w);
}
return workerStarted;
}
//worker也实现runnable接⼝
private final class Worker
extends AbstractQueuedSynchronizer
implements Runnable
{
//worker中塞了runnable⽅法+通过线程⼯⼚创建了⼀个线程,并将runnable⽅法塞进这个线程中,即重写了runnable⽅法Worker(Runnable firstTask){
setState(-1);// inhibit interrupts until runWorker
this.firstTask = firstTask;
this.thread =getThreadFactory().newThread(this);
}
//runnable调⽤run⽅法
public void run(){
runWorker(this);
}
final void runWorker(Worker w){
Thread wt = Thread.currentThread();
Runnable task = w.firstTask;//将work中的task取出来,即execute中我们写进去的runnable⽅法任务
w.firstTask = null;
w.unlock();// allow interrupts
boolean completedAbruptly = true;
try {
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(((), STOP)||
(Thread.interrupted()&&
(), STOP)))&&
!wt.isInterrupted())
wt.interrupt();
try {
beforeExecute(wt, task);
try {
task.run();//启动任务
afterExecute(task, null);
} catch (Throwable ex){
afterExecute(task, ex);
throw ex;
}
} finally {
task = null;
wpletedTasks++;
w.unlock();
}
}
completedAbruptly = false;
} finally {
processWorkerExit(w, completedAbruptly);
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。