记一次源码探索-线程池提交一个任务到底有多少个线程在运行

这次主要有一个这样的疑惑

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

于是发现下图所示
记一次源码探索-线程池提交一个任务到底有多少个线程在运行_第1张图片

可见一共有3个线程,一个事主线程,一个是worker里面不停取任务的线程,这个就是coresize所指示的线程,还有一个是真正的任务线程

你可能感兴趣的:(java)