java 线程池原理

简单介绍一下java Executors框架来管理线程池原理:
//创建一个线程数大小为3的线程池
Executors.newFixedThreadPool(3);


1、线程池中的线程如何创建?创建后保存在哪里?
public class ThreadPoolExecutor extends AbstractExecutorService {
    //用队列保存需要执行的任务
    private final BlockingQueue<Runnable> workQueue;
    //将Worker保存在HashSet中,Worker是什么?
    private final HashSet<Worker> workers = new HashSet<Worker>();

//Worker包装了Runnable
 private final class Worker
        extends AbstractQueuedSynchronizer
        implements Runnable
    {
       
        private static final long serialVersionUID = 6138294804551838833L;

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

      
        public void run() {
            runWorker(this);
        }
 //看execute方法
  public void execute(Runnable command) {
        if (command == null)
            throw new NullPointerException();
       
       
        int c = ctl.get();
        if (workerCountOf(c) < corePoolSize) {
           //重点来了,addWorker.好了这就是线程保存在哪里。
            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);
        }
        else if (!addWorker(command, false))
            reject(command);
    }
  
//addWorker源码
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;
            w = new Worker(firstTask);
            final Thread t = w.thread;
            if (t != null) {
                mainLock.lock();
                try {
                  
                    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;
    }  

线程池中的每个线程封装在workder中,然后保存在一个HashMap<Workder>中。

2、当任务多于线程的时候怎么执行?例如有5个任务但是只有只创建了3个线程。
看Worker中的run方法调用的是runWorker方法:
 final void runWorker(Worker w) {
        Thread wt = Thread.currentThread();
        Runnable task = w.firstTask;
        w.firstTask = null;
        w.unlock(); // allow interrupts
        boolean completedAbruptly = true;
        try {
            //循环获取Runnable,getTask()方法从workQueue中获取任务
            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);
        }
    }

很显然这是生产者消费者模式的体现。runWorker循环阻塞等待从workQueue中取出任务。然后执行。

总结线程池原理:
线程池在执行线程的时候创建线程。然后执行完的线程并没有立即销毁而是阻塞等待 workQueue中来新任务然后接着执行。线程池也是生产者消费者模式的体现。

猜你喜欢

转载自chen-sai-201607223902.iteye.com/blog/2373842