Java 并发

线程池之运行过程原理

2020-02-11  本文已影响0人  Real_man

在刚开始提交任务的时候,线程池会创建核心线程,等核心线程创建完毕,开始将任务加入阻塞队列,队列满了之后最后才创建非核心线程。

线程池中每一个具体的线程运行过程是什么样的?

1 在创建Worker线程的时候,如果成功创建,会立刻调用start方法。

//在addWorker()部分
w = new Worker(firstTask);
final Thread t = w.thread;
...
if (workerAdded) {
    t.start();
    workerStarted = true;
}

2 看一下Worker类的结构,便可以了解到Worker线程在start之后做了什么事情

Worker(Runnable firstTask) {
       setState(-1); // inhibit interrupts until runWorker
       this.firstTask = firstTask;
             this.thread = getThreadFactory().newThread(this);
}

public void run() {
       runWorker(this);
}

从上面我们可以知道了,在Worker创建之后就会启动,调用runWorker方法。

3 简化一下runWorker的流程

关键点:

    final void runWorker(Worker w) {
        Thread wt = Thread.currentThread();
        
        Runnable task = w.firstTask;
        w.firstTask = null;
        w.unlock(); // allow interrupts
        // 代表着Worker是否因为用户的程序有问题导致的死亡
        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 (Exception x) {
                                                //... 不同的异常处理
                    } finally {
                        afterExecute(task, thrown);
                    }
                } finally {
                    task = null;
                    w.completedTasks++;
                    w.unlock();
                }
            }
            completedAbruptly = false;
        } finally {
            processWorkerExit(w, completedAbruptly);
        }
    }

4 getTask做了那些事情呢?

关键点:

    private Runnable getTask() {
        boolean timedOut = false; // Did the last poll() time out?

        for (;;) {
            int c = ctl.get();
            int rs = runStateOf(c);

                      // 2和3的情况
            // Check if queue empty only if necessary.
            if (rs >= SHUTDOWN && (rs >= STOP || workQueue.isEmpty())) {
                decrementWorkerCount();
                return null;
            }

            int wc = workerCountOf(c);
                        
                        // 1和4的情况
            // Are workers subject to culling?
            boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;
            if ((wc > maximumPoolSize || (timed && timedOut))
                && (wc > 1 || workQueue.isEmpty())) {
                if (compareAndDecrementWorkerCount(c))
                    return null;
                continue;
            }

            try {
                Runnable r = timed ?
                    workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
                    workQueue.take();
                if (r != null)
                    return r;
                timedOut = true;
            } catch (InterruptedException retry) {
                timedOut = false;
            }
        }
    }

5 worker的退出操作做了什么事情,completedAbruptly代表是否由于用户程序导致的线程退出

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; // replacement not needed
            }
            addWorker(null, false);
        }
    }

最后

在Worker执行的过程中,我们可以提炼几个问题:

1 Worker线程在什么时候开始执行?

2 Worker线程在什么情况下会退出?

3 什么情况下获取任务为空?

4 核心线程是否允许退出?如果可以,要怎么操作?

5 用户程序异常导致的Worker退出与Worker内部机制退出有什么区别?

如果以上回答都没问题,那么请联系我... 内推阿里

邮箱:aihe.ah@alibaba-inc.com

微信:aihehe5211

上一篇 下一篇

猜你喜欢

热点阅读