JAVA并发问题-线程池ThreadPool

JAVA中提供的线程池

Executors工厂类

Executors工具类提供了5种线程池的创建方法

    // 线程数动态创建,每个空闲线程会在默认60秒后被回收
    ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();
    // 固定线程数的线程池
    ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(10);
    // 定时器线程
    ScheduledExecutorService newScheduledThreadPool = Executors.newScheduledThreadPool(10);
    // 单线程,只有一个核心线程的线程池
    ExecutorService newSingleThreadExecutor = Executors.newSingleThreadExecutor();
    // fork/join线程池
    ExecutorService newWorkStealingPool = Executors.newWorkStealingPool();

每种线程池都有不同的作用,这里不一一展开,只从他们的原理说明。
我们看下这五种线程池的构造方法

public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue());
}
public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue());
}
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
        return new ScheduledThreadPoolExecutor(corePoolSize);
}
public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue()));
}
public static ExecutorService newWorkStealingPool() {
        return new ForkJoinPool
            (Runtime.getRuntime().availableProcessors(),
             ForkJoinPool.defaultForkJoinWorkerThreadFactory,
             null, true);
}

除了newScheduledThreadPoolnewWorkStealingPool,其他都是通过创建
ThreadPoolExecutor实现线程池.下面对ThreadPoolExecutor构造函数的参数进行了解。

public ThreadPoolExecutor(int corePoolSize, //核心线程数
                              int maximumPoolSize, // 最大线程数
                              long keepAliveTime, //空闲超时时间,worker线程无任务执行,等待时间
                              TimeUnit unit, //超时时间单位
                              BlockingQueue workQueue, //等待队列
                              ThreadFactory threadFactory, //线程工厂
                              RejectedExecutionHandler handler //拒绝策略
)

通过对ThreadPoolExecutor参数的不同设置,Executors创建了不同功能的线程池。

ThreadPoolExecutor的实现原理

ThreadPoolExecutor中包含属性Ctl使用高三位保存线程池的运行状态,低29位保存工作线程数,使用位运算进行操作。

    private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));

再看一下execute方法

public void execute(Runnable command) {
        if (command == null)
            throw new NullPointerException();
        int c = ctl.get();
        // 当前worker数量小于核心线程数 则添加worker
        if (workerCountOf(c) < corePoolSize) {
            if (addWorker(command, true))
                return;
            c = ctl.get();
        }
        // 如果超过核心线程数则尝试加入等待队列
        if (isRunning(c) && workQueue.offer(command)) {
            int recheck = ctl.get();
            // 如果这时有线程池shutdown了,把刚刚添加的移除
            if (! isRunning(recheck) && remove(command))
                //执行拒绝策略  
                reject(command);
            //  添加空worker
            else if (workerCountOf(recheck) == 0)
                //注意此时core参数为false,用于判断最大线程数
                addWorker(null, false);
        }
        // worker数量达到最大线程数,添加失败,拒绝
        else if (!addWorker(command, false))
            reject(command);
    }

再来看addWorker方法

private boolean addWorker(Runnable firstTask, boolean core) {
//第一部分开始 主要作用判断添加的worker是否超出数量
        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
            }
        }
// 第一部分结束
// 第二部分 添加worker信息,将线程信息封装worker对象,添加到workers(HashSet集合)
        boolean workerStarted = false;
        boolean workerAdded = false;
        Worker w = null;
        try {
            // 初始化了一个线程,firstTask为execute方法传入的线程实现。
            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) {
                    // 启动worker初始化是创建的线程
                    t.start();
                    workerStarted = true;
                }
            }
        } finally {
            if (! workerStarted)
                addWorkerFailed(w);
        }
// 第二部分结束
        return workerStarted;
    }

再来看下worker结构

    private final class Worker extends AbstractQueuedSynchronizer implements Runnable {
        final Thread thread;
        Runnable firstTask;
        volatile long completedTasks;
    }
       Worker(Runnable firstTask) {
            setState(-1); // inhibit interrupts until runWorker
            this.firstTask = firstTask;
            //通过传入当前worker对象创建线程
            this.thread = getThreadFactory().newThread(this);
        }
        public void run() {  
            runWorker(this);
        }

worker继承了AQS,通过实现lock和unlock方法实现任务的执行,防止执行过程中被中断。并且包含一个Thread.
当新建一个worker的时候创建了一个线程,而addWorker完成后启动了这个线程,而这个线程传入了worker,worker实现了runnable接口的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 {
            // 当前worker是不断循环,线程复用的地方是getTask,getTask从等待队列中获取任务,如果拿到任务了就继续运行。如果为空则销毁非核心线程worker
            while (task != null || (task = getTask()) != null) {
                // 这里的作用是当线程池shutdown时,不中断已经运行的线程
                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 {
                      //通过worker线程执行线程的run方法到达,线程池线程复用的作用
                        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 {
            // 执行完成移除worker,核心线程会被复用。核心线程如果需要回收需要设置allowCoreThreadTimeOut
            processWorkerExit(w, completedAbruptly);
        }
    }

线程池的核心是复用线程,更好的管理线程的创建。阿里P3C规范中不建议使用Executors创建线程池,原因是为了让使用者更好的控制ThreadPoolExecutor参数,实现自己想要的结果。
另外ThreadPoolExecutor提供submit方法支持传入Callable接口,并且带返回值。其实现原理是FutureTask维护任务的执行状态,通过Future.get()方法中判断任务未完成,则调用LockSupport.park挂起线程,当任务执行完成再unpark返回结果。

线程池大小的设置

  • 硬件和软件上的限制。
    • CPU核心数的考虑
    • 程序运行任务的类别,当时IO密集型的任务,则可以设置更多的线程数,例如设置CPU核心数*2。而如果是CPU密集型的任务,则设置更多线程数反而影响性能,例如可以设置CPU核心数+1。

你可能感兴趣的:(JAVA并发问题-线程池ThreadPool)