// 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方法,即执行任务。
}
}
线程池运行顺序:
java线程池ThreadPoolExecutor(三)——线程池中是如何执行任务的? 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方法。
/*
创建线程池的时候,实际上还没有创建线程,只是弄了一个框架,在执行到下面这段的时候才开创建。
创建线程池之后,进入
threadPool.execute(()->{
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++) {
// 使用了线程池之后,使用线程池来创建线程
threadPool.execute(()->{
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 = ctl.get();
}
private boolean addWorker(Runnable firstTask, boolean core) {
retry:
for (int c = ctl.get();;) {
// 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 = ctl.get(); // Re-read 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 = ctl.get();
if (isRunning(c) ||
(runStateLessThan(c, STOP) && firstTask == null)) {
if (t.getState() != 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 ((runStateAtLeast(ctl.get(), STOP) ||
(Thread.interrupted() &&
runStateAtLeast(ctl.get(), 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;
w.completedTasks++;
w.unlock();
}
}
completedAbruptly = false;
} finally {
processWorkerExit(w, completedAbruptly);
}
}