Java线程池浅谈

今天来谈一谈Java线程池如何“归还”线程,你们都知道数据库链接池使用完成后须要将链接还回链接池。Java线程池中的线程使用完后需不须要归还,如何归还呢,想了半天没想明白,看了JDK源代码后搞明白了。数据库

核心代码都在ThreadPoolExecutor类里。oop

首先建立线程池时,设置corePoolSize、maximumPoolSize。意思很明白,很少解释。ui

而后当调用线程池的execute方法时,若是当前线程池里的线程数比corePoolSize小,则直接建立一个新的线程,这个地方有个巧妙的处理,并非直接new Thread,而是建立一个Worker对象。this

Worker类实现了Runnable接口,以下图所示:spa

private final class Worker
    extends AbstractQueuedSynchronizer
    implements Runnable

并持有一个Thread对象,该Thread对象包装了Worker的Runnable接口,以下图所示:线程

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

Worker的run方法以下:对象

/** Delegates main run loop to outer runWorker  */
public void run() {
    runWorker(this);
}
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);
    }
}

Worker的run方法执行时会从一个队列里获取Runnable接口的实现,即上图的getTask方法,获取到后执行task的run方法。接口

核心部分都已经展现完了,让咱们把他们串联起来。队列

线程池的execute方法执行时建立一个Worker,而后执行Worker持有的线程的start方法,其实也就是启动了一个线程。该线程执行Worker的run方法,由于Worker也实现了Runnable接口。run执行时首先从队列获取任务,有的话就执行其run方法,不是start方法,因此并无新启动线程。该线程执行完成后,若是队列中有任务,那么该线程会继续执行新的任务,实现了线程复用。get

因此线程池里的线程并不须要显式归还。

相关文章
相关标签/搜索