前面我们对并发有了一定的认识,并且知道如何创建线程,创建线程主要依靠的是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. A9

    今日内容: 解决队友提出的问题 明日计划: 商讨界面还有哪些不足的地方 困难: 每天大部分时间被电工实习占走了

  2. iOS- Swift:如何使用iOS8中的UIAlertController

    1.前言 在前段时间手机QQ:升级iOS8.3后,发图就崩的情况, 就是因为iOS8更新UIAlertController后,仍然使用UIAlertview导致的 具体原因分析 这个可以看腾讯团队发出 ...

  3. php获取指定div内容

    <?php $p="http://127.0.0.1:8080/website/index.html"; $ch = curl_init(); curl_setopt($ch ...

  4. PHP伪类型和伪变量

    一.伪类型 PHP伪类型有三种,分别是:1,mixed混合类型.2,number数字类型.3,callback回调类型. 1,mixed混合类型: mixed说明一个参数可以接受多种不同的类型,但并不 ...

  5. MySQL存储引擎InnoDB与Myisam

    InnoDB与Myisam的六大区别 InnoDB与Myisam的六大区别 MyISAM InnoDB 构成上的区别: 每个MyISAM在磁盘上存储成三个文件.第一个 文件的名字以表的名字开始,扩展名 ...

  6. idea导出包含main函数的jar

    1.首先打开File->project stucture->Artifacts 2.按照下图方式: 3.选择面main函数的所在的类,选择MAINFEST.MF问的生成路径 这里一定选择 ...

  7. EM算法[转]

    最大期望算法:EM算法. 在统计计算中,最大期望算法(EM)是在概率模型中寻找参数最大似然估计或者最大后验估计的算法,其中概率模型依赖于无法观测的隐藏变量. 最大期望算法经过两个步骤交替进行计算: 第 ...

  8. 【HLSDK系列】Delta 详解

    服务端和客户端总是需要互相交换数据,来做到实时的游戏体验. 很久之前,我们的网速都不是很快,甚至带宽只有 1Mbps (128KB/s)这样的速度,作为当时一个网络实时对战游戏,每时每刻都要传递数据, ...

  9. 在洛谷3369 Treap模板题 中发现的Splay详解

    本题的Splay写法(无指针Splay超详细) 前言 首先来讲...终于调出来了55555...调了整整3天..... 看到大部分大佬都是用指针来实现的Splay.小的只是按照Splay的核心思想和原 ...

  10. 深入理解JVM一java堆分析

    上一节介绍了针对JVM的监控工具,包括JPS可以查看当前所有的java进程,jstack查看线程栈可以帮助你分析是否有死锁等情况,jmap可以导出java堆文件在MAT工具上进行分析等等.这些工具都非 ...