推荐:Java并发编程汇总

Java并发编程一线程池简介

为什么我们需要使用线程池?

我们知道线程是一种比较昂贵的资源,我们通过程序每创建一个线程去执行,其实操作系统都会对应地创建一个线程去执行我们的任务,而我们频繁的创建、销毁线程是非常耗费系统资源的,当并发数不大时,对系统似乎没什么影响,但当并发数很大时,我们为每一个请求都去创建一个线程,然后等待被调度、执行完任务后再销毁,这样频繁的创建、销毁线程是很耗费系统资源的。

而我们使用线程池去管理线程,就可以很好的减少这种损耗,因为线程池会复用线程,什么是复用线程呢?就是线程池里面的线程,并不和我们自己创建一个线程去执行单个任务一样,执行完这个任务线程就结束了,而线程池中的线程,它的执行逻辑中有一个while循环,在这个while循环中,线程会不断的去获取任务,然后执行(有任务的情况下),如果在高并发环境下,这会极大的减少线程的创建与销毁操作,节约系统的资源。

我们来看一看线程池的部分源码:

    final void runWorker(Worker w) {Thread wt = Thread.currentThread();Runnable task = w.firstTask;w.firstTask = null;w.unlock(); // allow interruptsboolean 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 interruptif ((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);}}

Repeatedly gets tasks from queue and executes them这是上面这个方法的一段注释,从方法的代码和注释中,都很明显的展现了线程池中的线程并不是执行完一个任务就结束了,而是会主动(重复)去获取任务,然后执行。

线程池的设计

很明显是面向接口编程。

线程池的一些属性


下面是这些属性的源码与注释,结合上图应该不难看懂。

    /*** Core pool size is the minimum number of workers to keep alive* (and not allow to time out etc) unless allowCoreThreadTimeOut* is set, in which case the minimum is zero.*/private volatile int corePoolSize;
    /*** Maximum pool size. Note that the actual maximum is internally* bounded by CAPACITY.*/private volatile int maximumPoolSize;
    /*** Timeout in nanoseconds for idle threads waiting for work.* Threads use this timeout when there are more than corePoolSize* present or if allowCoreThreadTimeOut. Otherwise they wait* forever for new work.*/private volatile long keepAliveTime;
   /*** The queue used for holding tasks and handing off to worker* threads.  We do not require that workQueue.poll() returning* null necessarily means that workQueue.isEmpty(), so rely* solely on isEmpty to see if the queue is empty (which we must* do for example when deciding whether to transition from* SHUTDOWN to TIDYING).  This accommodates special-purpose* queues such as DelayQueues for which poll() is allowed to* return null even if it may later return non-null when delays* expire.*/private final BlockingQueue<Runnable> workQueue;
    /*** Factory for new threads. All threads are created using this* factory (via method addWorker).  All callers must be prepared* for addWorker to fail, which may reflect a system or user's* policy limiting the number of threads.  Even though it is not* treated as an error, failure to create threads may result in* new tasks being rejected or existing ones remaining stuck in* the queue.** We go further and preserve pool invariants even in the face of* errors such as OutOfMemoryError, that might be thrown while* trying to create threads.  Such errors are rather common due to* the need to allocate a native stack in Thread.start, and users* will want to perform clean pool shutdown to clean up.  There* will likely be enough memory available for the cleanup code to* complete without encountering yet another OutOfMemoryError.*/private volatile ThreadFactory threadFactory;
    /*** Handler called when saturated or shutdown in execute.*/private volatile RejectedExecutionHandler handler;


线程池结构

线程池创建线程

这个图是中文的,应该很生动了,就不需要解释了吧。

线程池拒绝任务

当线程池的任务队列满了,并且无法再创建新的线程了(线程数量达到maximumPoolSize),线程池就会拒绝任务。其实还有其他情况线程池也会拒绝任务,这里只是简单让大家知道,线程池是会拒绝任务的。

这里只是让大家对Java线程池有一个大概的了解,并没有详细讲解原理,毕竟博主也是初学者,以后有机会会再进行补充的。

Java并发编程一线程池简介相关推荐

  1. 【Java 并发编程】线程池机制 ( ThreadPoolExecutor 线程池构造参数分析 | 核心线程数 | 最大线程数 | 非核心线程存活时间 | 任务阻塞队列 )

    文章目录 前言 一.ThreadPoolExecutor 构造参数 二.newCachedThreadPool 参数分析 三.newFixedThreadPool 参数分析 四.newSingleTh ...

  2. 【Java 并发编程】线程池机制 ( 线程池示例 | newCachedThreadPool | newFixedThreadPool | newSingleThreadExecutor )

    文章目录 前言 一.线程池示例 二.newCachedThreadPool 线程池示例 三.newFixedThreadPool 线程池示例 三.newSingleThreadExecutor 线程池 ...

  3. (转)Java并发编程:线程池的使用

    背景:线程池在面试时候经常遇到,反复出现的问题就是理解不深入,不能做到游刃有余.所以这篇博客是要深入总结线程池的使用. ThreadPoolExecutor的继承关系 线程池的原理 1.线程池状态(4 ...

  4. [转]Java并发编程:线程池的使用

    Java并发编程:线程池的使用 在前面的文章中,我们使用线程的时候就去创建一个线程,这样实现起来非常简便,但是就会有一个问题: 如果并发的线程数量很多,并且每个线程都是执行一个时间很短的任务就结束了, ...

  5. Java并发编程一线程池的五种状态

    推荐:Java并发编程汇总 Java并发编程一线程池的五种状态 原文地址 Java多线程线程池(4)–线程池的五种状态 正文 线程池的5种状态:Running.ShutDown.Stop.Tidyin ...

  6. Java并发编程:线程池的使用

    在前面的文章中,我们使用线程的时候就去创建一个线程,这样实现起来非常简便,但是就会有一个问题: 如果并发的线程数量很多,并且每个线程都是执行一个时间很短的任务就结束了,这样频繁创建线程就会大大降低系统 ...

  7. Java并发编程之线程池及示例

    1.Executor 线程池顶级接口.定义方法,void execute(Runnable).方法是用于处理任务的一个服务方法.调用者提供Runnable 接口的实现,线程池通过线程执行这个 Runn ...

  8. 《Java 并发编程》线程池

    <Java 并发编程>专栏索引

  9. Java并发编程:线程池

    一.为什么使用线程池 使用线程的时候直接就去创建一个线程,这样实现起来非常简便,但是就会有一个问题: 如果并发的线程数量很多,并且每个线程都是执行一个时间很短的任务就结束了,这样频繁创建线程就会大大降 ...

最新文章

  1. 微博运营与微博营销最易犯的20种错误,你犯了吗?
  2. js 编码、解码与asp.net 编码、解码
  3. QDoc文件结构documentstructure
  4. python中链表和数组_数据结构笔记(一):数组、链表|python基础教程|python入门|python教程...
  5. 一步步编写操作系统 59 cpu的IO特权级1
  6. ext store 数据修改_extjs 之Ext.data.Store变更单行记录值【修改】
  7. IDEA工作笔记-自动生成POJO或JPA的实体类
  8. 电脑怎么在线录制屏幕声音,如何内录
  9. Abaqus齿轮链条传动仿真案例
  10. 机器学习算法——决策树3(CART决策树算法)
  11. Joson的简单用法
  12. 双绞线有两种接法:EIA/TIA 568B标准和EIA/TIA 568A标准。具体接法如下:
  13. 怎么刷android10,安卓10的刷机教程,教你刷好Killer的精简包
  14. JavaScript高级程序设计[美]Nicholas C.Zakas著 读书笔记(三)
  15. 便携式三星mysql_三星折叠手机终于来了!9 月 18 日正式发售
  16. 吕 思 伟 ---- 潘 爱 民 :: ATL 介 绍( 四)
  17. win10下自带输入法变为繁体字的原因及解决方法
  18. 四面深信服(长沙)软件测试工程师10k,大概是长沙双休犯法吧笑
  19. Bert入门:使用Bert运行MRPC的demo成功案例
  20. 小程序模拟表格-可左右滑动

热门文章

  1. 梦幻手游最新服务器,梦幻西游手游最新服务器合服公告 5月11日合服一览
  2. 苹果4s手机装 java微信_苹果4s版本过低不能下载微信怎么安装旧版本的
  3. 取模(余)%运算详解
  4. uniapp 打包成安卓app
  5. java doc转换docx_JAVA - 将doc文档转为docx文档
  6. 计算机图形学6--讨论多边形
  7. python 泰森多边形边界_泰森多边形
  8. [深入理解SSD 为SSD编程] SSD的架构和基准
  9. 【算法】3 由招聘问题看随机算法
  10. C++实现的简单k近邻算法(K-Nearest-Neighbour,K-NN)