java 并发 (线程池的使用)

          我们知道,并发的常规处理手段是使用多线程技术,但是当我们需要开启许多线程时,这是对线程进行管理是非常有必要的,频繁创建线程和销毁线程时非常消耗系统资源的,这里我们需要引入线程池的概念,是线程进行服用,执行完一个任务不被销毁,而是继续执行下一个任务,直到所有任务被执行完成。

          首先,我们来看一下线程池的核心类:ThreadPoolExecutor,贴上源码

       
public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory) {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
             threadFactory, defaultHandler);
    } 
public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              RejectedExecutionHandler handler) {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
             Executors.defaultThreadFactory(), handler);
    }    
public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory,
                              RejectedExecutionHandler handler) {
        if (corePoolSize < 0 ||
            maximumPoolSize <= 0 ||
            maximumPoolSize < corePoolSize ||
            keepAliveTime < 0)
            throw new IllegalArgumentException();
        if (workQueue == null || threadFactory == null || handler == null)
            throw new NullPointerException();
        this.acc = System.getSecurityManager() == null ?
                null :
                AccessController.getContext();
        this.corePoolSize = corePoolSize;
        this.maximumPoolSize = maximumPoolSize;
        this.workQueue = workQueue;
        this.keepAliveTime = unit.toNanos(keepAliveTime);
        this.threadFactory = threadFactory;
        this.handler = handler;
    }

对这几个参数进行分析:

corePoolSize:核心池的大小。在创建了线程池后,池中是没有任何线程的。直到有任务加入到线程池中,当线程池中的线程数量达到corePoolSize的大小时,会将之后的任务加入到缓存队列当中。

maximumPoolSize:线程最大数量,这表示在线程池中最多可以创建的线程数量

keepAliveTime:表示线程没有任务执行时会保持多久再停止。默认情况下 只有当线程数大于corePoolSize,keepAliveTime才会起作用

unit:keepAliveTime的单位

workQueue:一个阻塞队列,用于存储待执行的任务

threadFactory:线程工厂,用来创建线程

handler:表示当拒绝处理任务时的策略

ThreadPoolExecutor继承了AbstractExecutorService,AbstractExecutorService是一个抽象类,它实现了ExecutorService接口,而ExecutorService又是继承了Executor接口

ThreadPoolExecutor类中有几个很重要的方法:

execute()方法实际上是Executor中声明的方法,在ThreadPoolExecutor进行了具体的实现,这个方法是ThreadPoolExecutor的核心方法,通过这个方法可以向线程池提交一个任务,交由线程池去执行。

submit()方法是在ExecutorService中声明的方法,在AbstractExecutorService就已经有了具体的实现,在ThreadPoolExecutor中并没有对其进行重写,这个方法也是用来向线程池提交任务的,但是它和execute()方法不同,它能够返回任务执行的结果,去看submit()方法的实现,会发现它实际上还是调用的execute()方法,只不过它利用了Future来获取任务执行结果

shutdown()和shutdownNow()是用来关闭线程池的

关于线程的状态:

    private static final int RUNNING    = -1 << COUNT_BITS;
    private static final int SHUTDOWN   =  0 << COUNT_BITS;
    private static final int STOP       =  1 << COUNT_BITS;
    private static final int TIDYING    =  2 << COUNT_BITS;
    private static final int TERMINATED =  3 << COUNT_BITS;

当创建线程池后,初始时,线程池处于RUNNING状态

如果调用了shutdown()方法,则线程池处于SHUTDOWN状态,此时线程池不能够接受新的任务,它会等待所有任务执行完毕

如果调用了shutdownNow()方法,则线程池处于STOP状态,此时线程池不能接受新的任务,并且会去尝试终止正在执行的任务;

当线程池处于SHUTDOWN或STOP状态,并且所有工作线程已经销毁,任务缓存队列已经清空或执行结束后,线程池被设置为TERMINATED状态。

接下来我们关注excute()的具体实现,excute是很重要的方法

    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();
        if (workerCountOf(c) < corePoolSize) {
            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);
    }

jdk1.8中 采用院子操作类AtomicInteger 来获取当前线程状态,保证线程安全

如果运行的线程数小于核心线程数,则直接添加任务,并且更新线程状态

如果是运行状态下,并且添加任务到缓存队列成功,此时回重新获取线程状态用于校验,如果不通过校验并且将此次任务移除出缓存队列成功,就会拒绝这次添加任务的请求;如果队列中的任务数量为0,就会添加一个空任务

如果添加任务失败,则会尝试打断这次任务的添加。

猜你喜欢

转载自www.cnblogs.com/zhhouse/p/10506179.html