并发编程的艺术之读书笔记(十五)

前言:

上一部分,我们简单的学习了java的并发工具类,这部分我们开始学习java的线程池

1. 什么是线程池

线程池是一种多线程处理形式,处理过程中将任务添加到队列,然后在创建线程后自动启动这些任务。这避免了在处理短时间任务时创建与销毁线程的代价。java中的线程池是运用场景最多的并发框架,几乎所有需要异步或者并发执行任务的程序都可以使用线程池,在开发过程中,合理使用线程池可以带来3个好处。

1.降低资源消耗  重复利用已创建的线程降低线程创建和销毁带来的消耗

2.提高响应速度  任务到达时,可以不用等创建线程就立即执行

3.提高线程的可管理性 使用线程池可以统一分配、调优和监控线程 

2. 线程池的实现原理

当向线程池提交一个任务后,线程池是如何处理这个任务的呢,接下来我们看一下线程池的处理流程

从图可知,一个新任务提交到线程池时,线程池会这样处理

  1.  判断核心线程池是否都在执行任务,如果不是,创建一个新的工作线程来执行任务,如果核心线程池里的线程都在执行任务,则进入下一个流程
  2. 线程池判断工作队列是否已满,如果工作队列没有满,则新提交的任务存储在这个工作队列里,如果工作队列满了,则进入下一个流程
  3. 线程池判断线程池的线程是否都处在工作状态,如果没有,则创建一个新的工作线程来执行任务,如果已经满了,则交给饱和策略来处理这个任务

ThreadPoolExecutor执行execute方法的示意图如下

ThreadPoolExecutor执行execute()方法分四种情况

  1. 如果当前运行线程少于corePoolSize,则创建新线程来执行任务(注意,执行这一步需要获取全局锁)
  2. 如果运行的线程等于或少于corePoolSize,则将任务加入BlockingQueue
  3. 如果无法将任务加入BlockingQueue(队列满),则创建新的线程来处理任务(执行这一步需要获取全局锁)
  4. 如果创建新线程使当前运行线程超出maximunPoolSize,任务会被拒绝,调用RejectedExecutionHandler.rejectedExecution方法

下面我们来看一下excute的实现源码

    /**
     * Executes the given task sometime in the future.  The task
     * may execute in a new thread or in an existing pooled thread.
     *
     * If the task cannot be submitted for execution, either because this
     * executor has been shutdown or because its capacity has been reached,
     * the task is handled by the current {@code RejectedExecutionHandler}.
     *
     * @param command the task to execute
     * @throws RejectedExecutionException at discretion of
     *         {@code RejectedExecutionHandler}, if the task
     *         cannot be accepted for execution
     * @throws NullPointerException if {@code command} is null
     */
    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();
        // 如果当前线程数少于核心线程数,直接添加一个 worker 执行任务,
        // 创建一个新的线程,并把当前任务 command 作为这个线程的第一个任务(firstTask)
        if (workerCountOf(c) < corePoolSize) {
        // 添加任务成功,即结束
        // 执行的结果,会包装到 FutureTask 
        // 返回 false 代表线程池不允许提交任务
            if (addWorker(command, true))
                return;
           
            c = ctl.get();
        }

        // 到这说明,要么当前线程数大于等于核心线程数,要么刚刚 addWorker 失败
  
        // 如果线程池处于 RUNNING ,把这个任务添加到任务队列 workQueue 中
        if (isRunning(c) && workQueue.offer(command)) {
            /* 若任务进入 workQueue,我们是否需要开启新的线程
             * 线程数在 [0, corePoolSize) 是无条件开启新线程的
             * 若线程数已经大于等于 corePoolSize,则将任务添加到队列中,然后进到这里
             */
            int recheck = ctl.get();
            // 若线程池不处于 RUNNING ,则移除已经入队的这个任务,并且执行拒绝策略
            if (! isRunning(recheck) && remove(command))
                reject(command);
            // 若线程池还是 RUNNING ,且线程数为 0,则开启新的线程
            // 这块代码的真正意图:担心任务提交到队列中了,但是线程都关闭了
            else if (workerCountOf(recheck) == 0)
                addWorker(null, false);
        }
        // 若 workQueue 满,到该分支
        // 以 maximumPoolSize 为界创建新 worker,
        // 若失败,说明当前线程数已经达到 maximumPoolSize,执行拒绝策略
        else if (!addWorker(command, false))
            reject(command);
    }

工作线程:线程池创建线程时,会将线程封装成工作线程worker,worker在执行完任务后,还会循环获取工作队列里的任务来执行,我们来看一下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 {
            while (task != null || (task = getTask()) != null) {
                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);
        }
    }

ThreadPoolExecutor中线程执行任务的示意图如下

线程池中的线程执行任务分两种情况,一是execute()方法创建出一个线程时,让这个线程去执行任务,二是执行完1的任务后反复从BlockingQueue中获取任务执行。

3. 线程池的创建

我们可以通过ThreadPoolExecutor来创建一个线程池

new ThreadPoolExecutor(corePoolSize,maximumPoolSize,keepAlive,miliseconds,runnableTaskQueue,handler);

创建线程池需要的参数解释如下

1.corePoolSize 

表示线程池的常驻核心线程数。如果设置为0,则表示在没有任何任务时,销毁线程池;如果大于0,即使没有任务时也会保证线程池的线程数量等于此值。但需要注意,此值如果设置的比较小,则会频繁的创建和销毁线程,如果设置的比较大,则会浪费系统资源

2. maximumPoolSize 

表示线程池在任务最多时,最大可以创建的线程数。官方规定此值必须大于 0,也必须大于等于 corePoolSize,此值只有在任务比较多,且不能存放在任务队列时,才会用到。

3. keepAliveTime

表示线程的存活时间,当线程池空闲时并且超过了此时间,多余的线程就会销毁,直到线程池中的线程数量销毁的等于corePoolSize为止。

4.ThreadFactory

表示线程的创建工厂,此参数一般用的比较少,我们通常在创建线程池时不指定此参数,它会使用默认的线程创建工厂的方法来创建线程

//Executors.defaultThreadFactory() 默认的线程创建工厂 
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
             Executors.defaultThreadFactory(), defaultHandler);

5. runnableTaskQueue(任务队列)

  • ArrayBlockingQueue 是一个基于数组的有界阻塞队列,此队列按FIFO原则对元素排序
  • LinkedBlockingQueue 一个基于链表的阻塞队列,此队列按FIFO原则对元素排序,静态工厂方法Executors.newFixedThreadPool方法使用了这个队列
  • SynchronousQueue 一个不存储元素的阻塞队列,每个插入操作必须等到另一个线程调用移除操作,否则插入操作一直处于阻塞状态,静态工厂方法Executors.newCachedThreadPool方法使用了这个队列
  • PriorityBlockingQueue 一个具有优先级的无界阻塞队列

6. RejectedExecutionHandler(拒绝策略)

线程池的任务已经在缓存队列 workQueue 中存储满了之后,并且不能创建新的线程来执行此任务时,就会用到此拒绝策略,它属于一种限流保护的机制。java一共提供了四种拒绝策略

  • AbortPolicy 直接抛出异常
  • CallerRunsPolicy 只用调用者所在的线程来运行任务
  • DiscardOldestPolicy  丢弃队列里最近的一个任务,并执行当前任务
  • DiscardPolicy 不处理,丢弃掉

4. 向线程池提交任务

可以用两个方法向线程池提交任务,分别为execute方法和submit方法,execute用于提交不需要返回值的任务,submit用于提交需要返回值的任务,线程池会返回一个Future对象,通过Future对象可以判断任务是否执行成功,并且可以通过future的get方法来获取返回值,get方法会阻塞当前线程直到任务完成

首先我们看一下execute的使用演示

public class ThreadPoolExcutorTest {
    public static void main(String[] args) {
        ExecutorService service = Executors.newSingleThreadExecutor();
        for (int i = 0; i < 5; i++) {
            int finalI = i;
            service.execute(() -> {
                System.out.println("当前线程" + Thread.currentThread().getName() + " 执行第" + finalI + "次");
            });
        }
        service.shutdown();
    }
}


//结果
当前线程pool-1-thread-1 执行第0次
当前线程pool-1-thread-1 执行第1次
当前线程pool-1-thread-1 执行第2次
当前线程pool-1-thread-1 执行第3次
当前线程pool-1-thread-1 执行第4次

再看下submit的使用演示

public class ThreadPoolExcutorTest {
    public static void main(String[] args) {
        ExecutorService service = Executors.newSingleThreadExecutor();
        Future<String> future = service.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                System.out.println("submit方法执行完成,线程为:" + Thread.currentThread().getName());
                return "success";
            }
        });
        service.shutdown();
        try {
            String s = future.get();
            if("success".equals(s)){
                System.out.println("经过返回值比较,执行成功");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}

//结果
submit方法执行完成,线程为:pool-1-thread-1
经过返回值比较,执行成功

最后有一点,用完了线程池不要忘记调用threadPool.shutDown方法关闭线程池,它的原理是遍历线程池中的工作线程,然后逐个调用线程的interrupt方法中断线程,所以无法响应中断的线程可能永远无法结束。

总结

本部分我们一起学些了java的线程池的内容,下一部分我们将学习Executor框架的内容

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值