乐趣区

关于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 了一下,猜想是不是线程池提交一个工作后工作自身又起了一个线程,于是用一下代码验证一下

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());
        }
    }
}

于是发现下图所示

可见一共有 3 个线程,一个事主线程,一个是 worker 外面不停取工作的线程,这个就是 coresize 所批示的线程,还有一个是真正的工作线程

退出移动版