前面我们对并发有了一定的认识,并且知道如何创建线程,创建线程主要依靠的是Thread 的类来完成的,那么有什么缺陷呢?如何解决?

一、对比new Thread
new Thread的弊端
a. 每次new Thread新建对象性能差。
b. 线程缺乏统一管理,可能无限制新建线程,相互之间竞争,及可能占用过多系统资源导致死机或oom。
c. 缺乏更多功能,如定时执行、定期执行、线程中断。
相比new Thread,Java提供的四种线程池的好处在于:
a. 重用存在的线程,减少对象创建、消亡的开销,性能佳。
b. 可有效控制最大并发线程数,提高系统资源的使用率,同时避免过多资源竞争,避免堵塞。
c. 提供定时执行、定期执行、单线程、并发数控制等功能。

二、创建线程池方法

一般通过调用Executors的工厂方法创建线程池,常用的有以下5种类:

//创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待
Executors.newFixedThreadPool
//创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行
Executors.newSingleThreadExecutor
//创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程
Executors.newCachedThreadPool
//创建一个定长线程池,支持定时及周期性任务执行
Executors.newScheduledThreadPool
//创建一个单线程化的线程池,支持定时及周期性任务执行
Executors.newSingleThreadScheduledExecutor

上面每种出基本的参数使用外,还可以根据个人需要加入ThreadFactory(java的线程生成工厂,可以自己重写做些命名日志之类)参数。如:newFixedThreadPool有重载两种方法:newFixedThreadPool(int) 和 newFixedThreadPool(int,ThreadFactory)

调用上面的方法其实都是创建ThreadPoolExecutor对象,只是传入的参数不同而已。 
ThreadPoolExecutor的类方法:ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, ...),可定义线程池固定的线程数及最大线程数。

三、执行

一般通过调用execute(Runnable) 或者 submit(Callable)执行线程

四、关闭

详细可参考: 
深入理解JAVA–线程池(二):shutdown、shutdownNow、awaitTermination 
JAVA线程池shutdown和shutdownNow的区别 
threadPoolExecutor 中的 shutdown() 、 shutdownNow() 、 awaitTermination() 的用法和区别

threadPool.shutdown(): 不接受新任务,已提交的任务继续执行

Initiates an orderly shutdown in which previously submitted 
tasks are executed, but no new tasks will be accepted. 
Invocation has no additional effect if already shut down.

List<Runnable> shutdownNow(): 阻止新来的任务提交,同时会尝试中断当前正在运行的线程,返回等待执行的任务列表

Attempts to stop all actively executing tasks, halts the 
processing of waiting tasks, and returns a list of the tasks 
that were awaiting execution.

awaitTermination(long timeout, TimeUnit unit):等所有已提交的任务(包括正在跑的和队列中等待的)执行完或者超时或者被中断。

线程池状态: 
isShutdown():if this executor has been shut down. 
isTerminated():if all tasks have completed following shut down.isTerminated is never true unless either shutdown or shutdownNow was called first

如何选择: 
* 优雅的关闭,用shutdown() 
* 想立马关闭,并得到未执行任务列表,用shutdownNow() 
* 优雅的关闭,并允许关闭声明后新任务能提交,用awaitTermination()

五、常用线程池

newFixedThreadPool

要应用场景:固定线程数的线程池比较常见,如处理网络请求等。常用!!!

使用示例

/ 调用execute
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
for (int i = 0; i < 10; i++) {
final int index = i;
fixedThreadPool.execute(new Runnable() {
public void run() {
System.out.println(index);
});
} // 调用submit
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
List<Future> futureList = new ArrayList<Future>();
for (int i = 0; i < 10; i++) {
final int index = i;
futureList.add(fixedThreadPool.submit(new Callable<Integer>() {
public Integer call() throws Exception {
return index;
}
}));
}
for(Future future : futureList) {
try {
future.get();
} catch (Exception e) {
future.cancel(true);
}
}

newCachedThreadPool

主要应用场景:需要很极致的速度,因为newCachedThreadPool不会等待空闲线程。但有一定风险,如果一个任务很慢或者阻塞,并且请求很多,就容易造成线程泛滥,会导致整个系统的假死(无法接收处理新的请求),所以实际上个人不建议使用这个方法。

使用示例:execute、submit类似于newFixedThreadPool

ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
for (int i = 0; i < 10; i++) {
final int index = i;
cachedThreadPool.execute(new Runnable() {
public void run() {
System.out.println(index);
}
});
}

newSingleThreadExecutor

使用示例:execute、submit类似于newFixedThreadPool

ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
for (int i = 0; i < 10; i++) {
final int index = i;
singleThreadExecutor.execute(new Runnable() {
public void run() {
System.out.println(index);
});
}

newScheduledThreadPool

执行newScheduledThreadPool返回类ScheduledExecutorService(其实新建类ScheduledThreadPoolExecutor)。 
通过类ScheduledThreadPoolExecutor的定义:class ScheduledThreadPoolExecutor extends ThreadPoolExecutor implements ScheduledExecutorService及源码可知: 
1、ScheduledThreadPoolExecutor是ScheduledExecutorService的实现类。 
2、ScheduledThreadPoolExecutor继承了类ThreadPoolExecutor

通常我们通过Executors工厂方法(Executors.newScheduledThreadPool)获取类ScheduledExecutorService或直接通过new ScheduledThreadPoolExecutor类创建定时任务。

ScheduledThreadPoolExecutor有以下重载方法: 
方法返回接口:ScheduledFuture。接口定义为:public interface ScheduledFuture<V> extends Delayed, Future<V>。对应着有以下几种常用的方法: 
cancel:取消任务 
getDelay:获取任务还有多久执行


public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) 
延迟delay执行,只执行一次

使用示例

// 延迟3s执行
ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);
scheduledThreadPool.schedule(new Runnable() {
public void run() {
System.out.println("delay 3 seconds");
}
}, 3, TimeUnit.SECONDS); //延迟1秒后每3秒执行一次
ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);
ScheduledFuture<?> scheduledFuture = scheduledThreadPool.scheduleAtFixedRate(new Runnable() {
public void run() {
System.out.println("delay 1 seconds, and excute every 3 seconds");
}
}, 1, 3, TimeUnit.SECONDS); //获取下一次任务还有多久执行
scheduledFuture.getDelay(TimeUnit.SECONDS)

public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit)
延迟initialDelay开始执行执行,之后周期period执行,类比Timer的scheduleAtFixedRate方法,固定频率执行。当某个任务执行的时间超过period时间,则可能导致下一个定时任务延迟,但是不会出现并发执行的情况。当任何一个任务执行跑出异常,后面的任务将不会执行。所以你如果想保住任务都一直被周期执行,那么catch一切可能的异常。通过取消任务(调用cancel方法)或者终止executor(调用shutdown方法)可使任务停止。


public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) 
延迟initialDelay开始执行执行,之后周期period执行,类比Timer的schedule方法,固定延迟执行。当上一个任务执行后,等待delay时间才执行下一个,因此也不会并发执行的情况。当任何一个任务执行跑出异常,后面的任务将不会执行。所以你如果想保住任务都一直被周期执行,那么catch一切可能的异常。通过取消任务(调用cancel方法)或者终止executor(调用shutdown方法)可使任务停止。

六、ScheduledThreadPoolExecutor与Timer的区别

直接参考:Timer与ScheduledThreadPoolExecutor

参考:

java常用线程池 
Java 四种线程池的用法分析 
JAVA线程池shutdown和shutdownNow的区别

JAVA多线程提高六:java5线程并发库的应用_线程池的更多相关文章

  1. 使用Java线程并发库实现两个线程交替打印的线程题

    背景:是这样的今天在地铁上浏览了以下网页,看到网上一朋友问了一个多线程的问题.晚上闲着没事就决定把它实现出来. 题目: 1.开启两个线程,一个线程打印A-Z,两一个线程打印1-52的数据. 2.实现交 ...

  2. Java多线程与并发库高级应用-java5线程并发库

    java5 中的线程并发库 主要在java.util.concurrent包中 还有 java.util.concurrent.atomic子包和java.util.concurrent.lock子包 ...

  3. java--加强之 Java5的线程并发库

    转载请申明出处:http://blog.csdn.net/xmxkf/article/details/9945499 01. 传统线程技术回顾 创建线程的两种传统方式: 1.在Thread子类覆盖的r ...

  4. “全栈2019”Java多线程第六章:中断线程interrupt()方法详解

    难度 初级 学习时间 10分钟 适合人群 零基础 开发语言 Java 开发环境 JDK v11 IntelliJ IDEA v2018.3 文章原文链接 "全栈2019"Java多 ...

  5. 线程高级应用-心得8-java5线程并发库中同步集合Collections工具类的应用及案例分析

    1.  HashSet与HashMap的联系与区别? 区别:前者是单列后者是双列,就是hashmap有键有值,hashset只有键: 联系:HashSet的底层就是HashMap,可以参考HashSe ...

  6. 线程高级应用-心得5-java5线程并发库中Lock和Condition实现线程同步通讯

    1.Lock相关知识介绍 好比我同时种了几块地的麦子,然后就等待收割.收割时,则是哪块先熟了,先收割哪块. 下面举一个面试题的例子来引出Lock缓存读写锁的案例,一个load()和get()方法返回值 ...

  7. 线程高级应用-心得4-java5线程并发库介绍,及新技术案例分析

    1.  java5线程并发库新知识介绍 2.线程并发库案例分析 package com.itcast.family; import java.util.concurrent.ExecutorServi ...

  8. Java多线程之同步集合和并发集合

    Java多线程之同步集合和并发集合 不管是同步集合还是并发集合他们都支持线程安全,他们之间主要的区别体现在性能和可扩展性,还有他们如何实现的线程安全. 同步集合类 Hashtable Vector 同 ...

  9. “全栈2019”Java多线程第三十七章:如何让等待的线程无法被中断

    难度 初级 学习时间 10分钟 适合人群 零基础 开发语言 Java 开发环境 JDK v11 IntelliJ IDEA v2018.3 文章原文链接 "全栈2019"Java多 ...

随机推荐

  1. OpenCV学习笔记——图像平滑处理

    1.blur 归一化滤波器Blurs an image using the normalized box filter.C++: void blur(InputArray src, OutputArr ...

  2. myeclipse生成类的帮助文档

    http://blog.csdn.net/tabactivity/article/details/11807233

  3. 倒计时60s 代码

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  4. 1029 C语言文法翻译(2)

    program à external_declaration | program external_declaration 翻译:<源程序>→ <外部声明> | <源程序 ...

  5. Mac下使用svn命令

    Mac系统自带svn命令,能够很方便的同步更新代码,使用方法: 1.导入项目svn import /Users/username/Desktop/Project1 svn://192.168.1.12 ...

  6. bzoj1093[ZJOI2007]最大半连通子图(tarjan+拓扑排序+dp)

    Description 一个有向图G=(V,E)称为半连通的(Semi-Connected),如果满足:?u,v∈V,满足u→v或v→u,即对于图中任意两点u,v,存在一条u到v的有向路径或者从v到u ...

  7. 【bzoj2906】颜色 分块

    题目描述 给定一个长度为N的颜色序列C,对于该序列中的任意一个元素Ci,都有1<=Ci<=M.对于一种颜色ColorK来说,区间[L,R]内的权值定义为这种颜色在该区间中出现的次数的平方, ...

  8. Python 模板 Jinja2

    Python 模板 Jinja2 模板 要了解Jinja2,就需要先理解模板的概念.模板在Python的web开发中广泛使用,它能够有效的将业务逻辑和页面逻辑分开,使代码可读性更强.更加容易理解和维护 ...

  9. Day 2 while循环 编码 and or not

    1.判断下列逻辑语句的True,False. 1)1 > 1 or 3 < 4 or 4 > 5 and 2 > 1 and 9 > 8 or 7 < 6 Flas ...

  10. 【数据库_Mysql】查询当前年份的sql

    1.本年份 SELECT DATE_FORMAT(NOW(), '%Y'); 2.本月份(显示数字) SELECT DATE_FORMAT(NOW(), '%m'); 3.本月份(显示英文) SELE ...