线程池问题——主线程跑完,线程池是否会继续运行

关于使用线程池,主线程跑完,线程池是否会继续运行的问题

	public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        for (int i = 0; i < 20; i++) {
            int finalI = i;
            executorService.execute(() -> {
                System.out.println("xxxxxxxxx" + finalI);
                System.out.println(Thread.currentThread().getName());
            });
        }
        System.out.println("----------结束");
    }

运行完上段代码,是否会打印0到20?

----------结束
xxxxxxxxx1
pool-1-thread-2
xxxxxxxxx2
pool-1-thread-2
// 中间省略
xxxxxxxxx19
pool-1-thread-2
xxxxxxxxx17
pool-1-thread-1

会打印,原因是什么?
按一般的理解,主线程完成后executorService 对象就会终结,里面的workQueue这个队列也就不存在了。
看部分ThreadPoolExecutor源码,关键看又注释的几行

public class ThreadPoolExecutor extends AbstractExecutorService {
	
	// 任务队列
	private final BlockingQueue<Runnable> workQueue;
	// 存放着运行的线程
	private final HashSet<Worker> workers = new HashSet<Worker>();
	
	// 这是执行的入口
	 private boolean addWorker(Runnable firstTask, boolean core) {
        retry:
        for (;;) {
            int c = ctl.get();
            int rs = runStateOf(c);

            if (rs >= SHUTDOWN &&
                ! (rs == SHUTDOWN &&
                   firstTask == null &&
                   ! workQueue.isEmpty()))
                return false;

            for (;;) {
                int wc = workerCountOf(c);
                if (wc >= CAPACITY ||
                    wc >= (core ? corePoolSize : maximumPoolSize))
                    return false;
                if (compareAndIncrementWorkerCount(c))
                    break retry;
                c = ctl.get(); 
                if (runStateOf(c) != rs)
                    continue retry;
            }
        }

        boolean workerStarted = false;
        boolean workerAdded = false;
        Worker w = null;
        try {
            w = new Worker(firstTask); // 创建一个执行的线程
            final Thread t = w.thread;
            if (t != null) {
                final ReentrantLock mainLock = this.mainLock;
                mainLock.lock();
                try {
                    int rs = runStateOf(ctl.get());
                    if (rs < SHUTDOWN ||
                        (rs == SHUTDOWN && firstTask == null)) {
                        if (t.isAlive()) // precheck that t is startable
                            throw new IllegalThreadStateException();
                        workers.add(w);
                        int s = workers.size();
                        if (s > largestPoolSize)
                            largestPoolSize = s;
                        workerAdded = true;
                    }
                } finally {
                    mainLock.unlock();
                }
                if (workerAdded) {
                    t.start(); // 会调用Worker的run()方法
                    workerStarted = true;
                }
            }
        } finally {
            if (! workerStarted)
                addWorkerFailed(w);
        }
        return workerStarted;
    }
    
	// Worker 是内部类,所以有对ThreadPoolExecutor对象的引用,又因为实现了Runnable接口,所以相当于一个新线程持有对主线程创建的ThreadPoolExecutor对象的引用,所以不会被销毁
	private final class Worker extends AbstractQueuedSynchronizer implements Runnable{
		public void run() {
            runWorker(this); // 再调回ThreadPoolExecutor的runWorker()方法
        }
	}
	
	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) { // getTask()方法,不断从队列中拿任务执行,没有就阻塞
                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);// 这个很重要,当getTask()因为超时为获取或者其他原因返回null时运行
        }
    }
	
	private void processWorkerExit(Worker w, boolean completedAbruptly) {
        if (completedAbruptly) // If abrupt, then workerCount wasn't adjusted
            decrementWorkerCount();

        final ReentrantLock mainLock = this.mainLock;
        mainLock.lock();
        try {
            completedTaskCount += w.completedTasks;
            workers.remove(w);// 删除线程
        } finally {
            mainLock.unlock();
        }

        tryTerminate(); // 尝试终止

        int c = ctl.get();
        if (runStateLessThan(c, STOP)) {
            if (!completedAbruptly) {
                int min = allowCoreThreadTimeOut ? 0 : corePoolSize;
                if (min == 0 && ! workQueue.isEmpty())
                    min = 1;
                if (workerCountOf(c) >= min)
                    return;
            }
            addWorker(null, false); // 如果未终止,又回到入口方法处
        }
    }
}
        
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值