ThreadPoolExecutor
线程池对象,如果里面添加了任务,如果不手动调用 shutdown
方法,那么这个对象永远不会被 GC
首先看一下 ThreadPoolExecutor
的源码结构
ThreadPoolExecutor
里面有一个内部类 Worker
这个内部类实现了 Runnable
接口
这个 Worker
类里有一个 runWorker
方法,是保证线程不断运行的原理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| 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); } }
|
最外层的 while 循环不断调用 getTask()
方法从队列中取任务,如果取不到,就属于异常情况,把 completedAbruptly
设置为 false,进入 processWorkerExit
方法