java线程池的理解

线程池之前一定有多线程的概念,使用线程的时候就去创建一个线程
如果并发的线程数量很多,并且每个线程都是执行一个时间很短的任务就结束了,这样频繁创建线程就会大大降低系统的效率,因为频繁创建线程和销毁线程需要时间。
在Java中可以通过线程池,使得线程可以复用,就是执行完一个任务,并不被销毁,而是可以继续执行其他的任务


Executors创建线程池

Java 创建线程池的方法很简单,只需要调用Executors中相应的便捷方法即可:

newFixedThreadPool(int nThreads) 创建固定大小的线程池,可控制线程最大并发数,超出的线程任务会在队列中等待
newCachedThreadPool() 线程池为无限大,当执行第二个任务时第一个任务已经完成,会复用执行第一个任务的线程,而不用每次新建线程
newScheduledThreadPool(int corePoolSize) 调度型线程池,支持定时及周期性任务执行
newSingleThreadExecutor() 创建只有一个线程的线程池,任意时间池中只能有一个线程

Executors中创建线程池的快捷方法,实际上是都调用了ThreadPoolExecutor的构造方法

public ThreadPoolExecutor(int corePoolSize,//线程池长期维持的线程数,即使线程处于闲置状态,也不会回收
                          int maximumPoolSize,//线程池最大的线程数,也就是说是线程数的上限
                          long keepAliveTime,//当线程数大于长期维持的线程数corePoolSize,并且大于corePoolSize的线程空闲时长超过了这个时间,多余的线程会被回收
                          TimeUnit unit,//时间单位
                          BlockingQueue workQueue,//任务的排队队列
                          ThreadFactory threadFactory,// 新线程的产生方式
                          RejectedExecutionHandler handler)// 拒绝策略

线程池的任务处理策略:

如果当前线程池中的线程数目小于corePoolSize,则每来一个任务,就会创建一个线程去执行这个任务;

如果当前线程池中的线程数目>=corePoolSize,则每来一个任务,会尝试将其添加到任务缓存队列当中,若添加成功,则该任务会等待空闲线程将其取出去执行;若添加失败(一般来说是任务缓存队列已满),则会尝试创建新的线程去执行这个任务;如果当前线程池中的线程数目达到maximumPoolSize,则会采取任务拒绝策略进行处理;

如果线程池中的线程数量大于 corePoolSize时,如果某线程空闲时间超过keepAliveTime,线程将被终止,直至线程池中的线程数目不大于corePoolSize;如果允许为核心池中的线程设置存活时间,那么核心池中的线程空闲时间超过keepAliveTime,线程也会被终止。

处理的流程图:

java线程池的理解_第1张图片

队列

阻塞队列与普通队列的区别在于,当队列是空的时,从队列中获取元素的操作将会被阻塞,或者当队列是满时,往队列里添加元素的操作会被阻塞。

LinkedBlockingQueue()基于链表的FIFO阻塞队列
PriorityBlockingQueue() 带优先级的无界阻塞队列
SynchronousQueue()并发同步阻塞队列
ArrayBlockingQueue(int capacity)基于数组的并发阻塞队列
ConcurrentLinkedQueue()基于链表的并发队列

put(E e)
队列添加元素,可阻塞方法,等待有空间。
offer(E e)
队列添加元素,已满无法添加,会直接返回false
poll()
获取队列元素,无元素,会直接返回false
take()
获取队列元素,可阻塞方法,等待有元素。


拒绝策略

任务队列总有占满的时候,这是再submit()提交新的任务会怎么样呢?这个时候就用到了拒绝策略

java线程池的理解_第2张图片

拒绝策略 拒绝行为
AbortPolicy 抛出RejectedExecutionException
DiscardPolicy 什么也不做,直接忽略,多余的任务会悄悄的被忽略
DiscardOldestPolicy 丢弃执行队列中最老的任务,尝试为当前提交的任务腾出位置
CallerRunsPolicy 直接由提交任务者执行这个任务

 

线程池默认的拒绝行为是AbortPolicy(),会抛出异常.

 

三种提交任务的方式

 

提交方式 是否关心返回结果
Future submit(Callable task)
void execute(Runnable command)
Future submit(Runnable task) 否,虽然返回Future,但是其get()方法总是返回null

       execute() 通过这个方法可以向线程池提交一个任务,交由线程池去执行。

源码分析

execute()是线程池的核心方法,源码分析就从它展开:
public void execute(Runnable command) {
    if (command == null)
        throw new NullPointerException();
    /*
     * Proceed in 3 steps:
     *
     * 1. If fewer than corePoolSize threads are running, try to
     * start a new thread with the given command as its first
     * task.  The call to addWorker atomically checks runState and
     * workerCount, and so prevents false alarms that would add
     * threads when it shouldn't, by returning false.
     *
     * 2. If a task can be successfully queued, then we still need
     * to double-check whether we should have added a thread
     * (because existing ones died since last checking) or that
     * the pool shut down since entry into this method. So we
     * recheck state and if necessary roll back the enqueuing if
     * stopped, or start a new thread if there are none.
     *
     * 3. If we cannot queue task, then we try to add a new
     * thread.  If it fails, we know we are shut down or saturated
     * and so reject the task.
     */
    int c = ctl.get();
//判断如果当前线程数小于corePoolSize, 则创建新的核心worker对象
    if (workerCountOf(c) < corePoolSize) {
        if (addWorker(command, true))
            return;
        c = ctl.get();
    }
// 判断如果当前线程数大于corePoolSize, 并偿试放入队列 workQueue.offer(command) , 放入成功后等待线程池调度
//疑问:队列中的任务是什么时候取出来的?
    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);
    }
//偿试放入队列 workQueue.offer(command) 失败, 增加一个非core的线程
    else if (!addWorker(command, false))
        reject(command);
}

excute()方法中添加任务的方式是使用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 {
        w = new Worker(firstTask);//创建线程
        final Thread t = w.thread;
        if (t != null) {
            final ReentrantLock mainLock = this.mainLock;
            mainLock.lock();
            try {
                // Recheck while holding lock.
                // Back out on ThreadFactory failure or if
                // shut down before lock acquired.
                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;
}

线程启动后,又做了哪些工作:

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) {//getTask()从队列中获取任务,当前线程要在当前task执行完后才能执行下一个任务
            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);
    }
}

你可能感兴趣的:(编程)