此次主要有一個這樣的疑惑java
final void runWorker(Worker w) { Thread wt = Thread.currentThread(); Runnable task = w.firstTask; 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); 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); } }
這裏的話,task又run了一下,猜想是否是線程池提交一個任務後任務自己又起了一個線程,因而用一下代碼驗證一下ui
public class ThreadPool { private static ExecutorService pool; public static void main( String[] args ) { //maximumPoolSize設置爲2 ,拒絕策略爲AbortPolic策略,直接拋出異常 pool = new ThreadPoolExecutor(2, 10, 1000, TimeUnit.MILLISECONDS, new SynchronousQueue<Runnable>(), Executors.defaultThreadFactory(),new ThreadPoolExecutor.AbortPolicy()); for(int i=0;i<3;i++) { pool.execute(new ThreadTask()); } } public static class ThreadTask implements Runnable{ public ThreadTask() { } public void run() { System.out.println(Thread.currentThread().getName()); } } }
因而發現下圖所示spa
可見一共有3個線程,一個事主線程,一個是worker裏面不停取任務的線程,這個就是coresize所指示的線程,還有一個是真正的任務線程線程