美文网首页
java线程池

java线程池

作者: 小生_chen | 来源:发表于2019-01-05 18:31 被阅读0次

我们平时大部分大部分业务都会用到线程池,首先用线程池的一个好处在于它能复用线程,之前一直有疑问它是如何复用的,今天我们来看看里面的具体实现。

首先我们来看下线程池提交任务的方法ThreadPoolExecutor execute(Runnable command)

public void execute(Runnable command) {
        if (command == null)
            throw new NullPointerException();
      
        int c = ctl.get();
       //判断当前的线程数是否小于核心线程数
        if (workerCountOf(c) < corePoolSize) {
            //新增线程执行command 
            if (addWorker(command, true))
                return;
            c = ctl.get();
        }
        if (isRunning(c) && workQueue.offer(command)) {
            //如果线程池正常运行 并且成功加入任务队列
            int recheck = ctl.get();
            if (! isRunning(recheck) && remove(command))
                reject(command);
            else if (workerCountOf(recheck) == 0)//当现在没有线程的时候
                addWorker(null, false);//注意这里方法第一个参数是null ??? 下面我们看看里面用这个参数的意义
        }
        else if (!addWorker(command, false))
            reject(command);
    }

在上面的代码中我们可以看到addWorker方法的传参出现了两种形式,一种是直接传任务 一种是传null 我们下面看看里面到底是怎么运行的。

private boolean addWorker(Runnable firstTask, boolean core) {
        retry:
        for (;;) {
            int c = ctl.get();
            int rs = runStateOf(c);

            // Check if queue empty only if necessary.
            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();  // Re-read ctl
                if (runStateOf(c) != rs)
                    continue retry;
                // else CAS failed due to workerCount change; retry inner loop
            }
        }
      ------------------上面可以省略·------------------
        boolean workerStarted = false;
        boolean workerAdded = false;
        Worker w = null;
        try {
            final ReentrantLock mainLock = this.mainLock;
            //这里会new一个工作线程 我们可以进去看下new Worker的实现其实就是开启了一个线程
            w = new Worker(firstTask);
            final Thread t = w.thread;
            if (t != null) {
                mainLock.lock();
                try {
                    // Recheck while holding lock.
                    // Back out on ThreadFactory failure or if
                    // shut down before lock acquired.
                    int c = ctl.get();
                    int rs = runStateOf(c);

                    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();
                    workerStarted = true;
                }
            }
        } finally {
            if (! workerStarted)
                addWorkerFailed(w);
        }
        return workerStarted;
    }

下面我们看下Worker里面的具体实现

 Worker(Runnable firstTask) {
            setState(-1); // inhibit interrupts until runWorker
            this.firstTask = firstTask;//这个就是外面传进来的任务
            this.thread = getThreadFactory().newThread(this);//new了一个自己作为线程本身
}

//t.start()执行的方法
 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 {
            //这里就是关键所在了 当我们传了firstTask的时候 会直接执行下面的逻辑
            //我们可以看到下面其实就是run方法
            //那当我们前面没传firstTask的时候它会做什么处理呢 我们看下getTask方法
            while (task != null || (task = getTask()) != null) {
                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);
        }
    }
private Runnable getTask() {
        boolean timedOut = false; // Did the last poll() time out?

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

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

            boolean timed;      // Are workers subject to culling?

            for (;;) {
                int wc = workerCountOf(c);
                timed = allowCoreThreadTimeOut || wc > corePoolSize;

                if (wc <= maximumPoolSize && ! (timedOut && timed))
                    break;
                if (compareAndDecrementWorkerCount(c))
                    return null;
                c = ctl.get();  // Re-read ctl
                if (runStateOf(c) != rs)
                    continue retry;
                // else CAS failed due to workerCount change; retry inner loop
            }
          ````````````上面是一些筛选条件········
          ///我们可以看到下面是从工作队列里面获取任务 返回出去
            try {
                Runnable r = timed ?
                    workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
                    workQueue.take();
                if (r != null)
                    return r;
                timedOut = true;
            } catch (InterruptedException retry) {
                timedOut = false;
            }
        }
    }

所以当线程池里没有线程的时候 addWorker(null, false) 会new一个线程从任务队列里面一个一个获取执行。

相关文章

网友评论

      本文标题:java线程池

      本文链接:https://www.haomeiwen.com/subject/bkllrqtx.html