1、new Thread的弊端

执行一个异步任务你还只是如下new Thread吗?

new Thread(new Runnable() {

    @Override
public void run() {
// TODO Auto-generated method stub
}
}).start();

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

Java通过Executors提供四种线程池,分别为:

newCachedThreadPool创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。

newFixedThreadPool 创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。

newScheduledThreadPool 创建一个定长线程池,支持定时及周期性任务执行。

newSingleThreadExecutor 创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。

1.CachedThreadPool

创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程

public class ThreadRunner implements Runnable{
private int num;
   private int timeout;
public ThreadRunner(int num,int timeout){
this.num = num;
this.timeout = timeout;
} @Override
public void run() {
System.out.println(Thread.currentThread().getName() + ":运行中,"+num);
try {
    TimeUnit.SECONDS.sleep(timeout);
     } catch (InterruptedException e) {
    e.printStackTrace();
     }
}
}
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; public class CacheThreadPoolMain {
public static void main(String[] args) {
ExecutorService pool = Executors.newCachedThreadPool();
for(int i = 1;i<21;i++){
pool.submit(new ThreadRunner(i,0));
}
pool.shutdown();
}
}

结果:

pool-1-thread-1:运行中,1
pool-1-thread-5:运行中,5
pool-1-thread-2:运行中,2
pool-1-thread-7:运行中,7
pool-1-thread-4:运行中,4
pool-1-thread-9:运行中,9
pool-1-thread-3:运行中,3
pool-1-thread-10:运行中,10
pool-1-thread-8:运行中,8
pool-1-thread-6:运行中,6
pool-1-thread-12:运行中,12
pool-1-thread-11:运行中,11
pool-1-thread-13:运行中,13
pool-1-thread-9:运行中,14
pool-1-thread-10:运行中,20
pool-1-thread-13:运行中,15
pool-1-thread-8:运行中,19
pool-1-thread-11:运行中,16
pool-1-thread-6:运行中,18
pool-1-thread-12:运行中,17

总结
- 池中线程时随着处理数据增加而增加
- 线程数并不是一直增加,如果有新任务需要执行时,首先查询池中是否有空闲线程并且还为到空闲截止时间,如果有,则使用空闲线程,如果没有,则创建新线程并放入池中。
- 用于执行一些生存期很短的异步型任务。不适用于IO等长延时操作,因为这可能会创建大量线程,导致系统崩溃。
- 使用SynchronousQueue作为阻塞队列,如果有新任务进入队列,必须队列中数据被其他线程处理,否则会等待。

2.FixedThreadPool

创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待

import java.util.concurrent.TimeUnit;

public class ThreadRunner implements Runnable{
private int num;
private int timeout;
public ThreadRunner(int num,int timeout){
this.num = num;
this.timeout = timeout;
} @Override
public void run() {
System.out.println(Thread.currentThread().getName() + ":运行中,"+num);
try {
TimeUnit.SECONDS.sleep(timeout);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; public class FixedThreadPoolMain {
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(3);//有一个固定大小的线程池 for(int i = 1;i<21;i++){
pool.submit(new ThreadRunner(i,2));
} pool.shutdown();
}
}

总结:
- 池中线程数量固定,不会发生变化

- 使用无界的LinkedBlockingQueue,要综合考虑生成与消费能力,生成过剩,可能导致堆内存溢出。


- 适用一些很稳定很固定的正规并发线程,多用于服务器

3.ScheduledExcutorPool

创建一个定长线程池,支持定时及周期性任务执行。

ScheduledThreadPool中常用的ScheduleAtFixedRate和ScheduleWithFixedDelay

* ScheduleAtFixedRate 每次执行时间为上一次任务开始起向后推一个时间间隔,
* 即每次执行时间为 :initialDelay, initialDelay+period, initialDelay+2*period, …;
* ScheduleWithFixedDelay 每次执行时间为上一次任务结束起向后推一个时间间隔,
* 即每次执行时间为:initialDelay, initialDelay+executeTime+delay, initialDelay+2*executeTime+2*delay
*
* ScheduleAtFixedRate 是基于固定时间间隔进行任务调度,
* ScheduleWithFixedDelay 取决于每次任务执行的时间长短,是基于不固定时间间隔进行任务调度
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit; public class ThreadRunner implements Runnable{
private final SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss.SSS"); private int num;
private int timeout;
public ThreadRunner(int num,int timeout){
this.num = num;
this.timeout = timeout;
} @Override
public void run() {
System.out.println(Thread.currentThread().getName() + ":当前时间:"+format.format(new Date())+",运行中,"+num);
try {
TimeUnit.SECONDS.sleep(timeout);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit; public class ScheduledExcutorPoolMain {
public static void main(String[] args) {
ScheduledExecutorService pool = Executors.newScheduledThreadPool(5);//线程池 // 从现在开始5秒钟之后,每隔10秒钟执行一次ThreadRunner
pool.scheduleAtFixedRate(new ThreadRunner(2,3), 5,10, TimeUnit.SECONDS); // 从现在开始5秒钟之后,每隔10秒钟执行一次job2
pool.scheduleWithFixedDelay(new ThreadRunner(3,3), 5, 10, TimeUnit.SECONDS); /**
* ScheduleAtFixedRate 每次执行时间为上一次任务开始起向后推一个时间间隔,
* 即每次执行时间为 :initialDelay, initialDelay+period, initialDelay+2*period, …;
* ScheduleWithFixedDelay 每次执行时间为上一次任务结束起向后推一个时间间隔,
* 即每次执行时间为:initialDelay, initialDelay+executeTime+delay, initialDelay+2*executeTime+2*delay
*
* ScheduleAtFixedRate 是基于固定时间间隔进行任务调度,
* ScheduleWithFixedDelay 取决于每次任务执行的时间长短,是基于不固定时间间隔进行任务调度
*/
}
}

总结:

- 线程池设计的定时任务类,每个调度任务都会分配到线程池中的一个线程去执行,也就是说,任务是并发执行,互不影响。


- 只有当调度任务来的时候,ScheduledExecutorService才会真正启动一个线程,其余时间ScheduledExecutorService都是出于轮询任务的状态

4.SingleThreadExecutor

创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照提交顺序被执行

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit; public class ThreadRunner implements Runnable{
private final SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss.SSS"); private int num;
private int timeout;
public ThreadRunner(int num,int timeout){
this.num = num;
this.timeout = timeout;
} @Override
public void run() {
System.out.println(Thread.currentThread().getName() + ":当前时间:"+format.format(new Date())+",运行中,"+num);
try {
TimeUnit.SECONDS.sleep(timeout);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; public class SingleThreadPool {
public static void main(String[] args) {
ExecutorService pool = Executors.newSingleThreadExecutor();
for(int i=1;i<21;i++){
pool.submit(new ThreadRunner(i,5));
}
pool.shutdown();
}
}

结果:

pool-1-thread-1:当前时间:15:53:35.883,运行中,1
pool-1-thread-1:当前时间:15:53:40.884,运行中,2
pool-1-thread-1:当前时间:15:53:45.884,运行中,3
pool-1-thread-1:当前时间:15:53:50.884,运行中,4
pool-1-thread-1:当前时间:15:53:55.884,运行中,5
pool-1-thread-1:当前时间:15:54:00.885,运行中,6
pool-1-thread-1:当前时间:15:54:05.885,运行中,7
pool-1-thread-1:当前时间:15:54:10.886,运行中,8
pool-1-thread-1:当前时间:15:54:15.886,运行中,9
pool-1-thread-1:当前时间:15:54:20.887,运行中,10
pool-1-thread-1:当前时间:15:54:25.887,运行中,11
pool-1-thread-1:当前时间:15:54:30.887,运行中,12
pool-1-thread-1:当前时间:15:54:35.888,运行中,13
pool-1-thread-1:当前时间:15:54:40.888,运行中,14
pool-1-thread-1:当前时间:15:54:45.888,运行中,15
pool-1-thread-1:当前时间:15:54:50.888,运行中,16
pool-1-thread-1:当前时间:15:54:55.889,运行中,17
pool-1-thread-1:当前时间:15:55:00.889,运行中,18
pool-1-thread-1:当前时间:15:55:05.889,运行中,19
pool-1-thread-1:当前时间:15:55:10.890,运行中,20

总结:

- 线程中只有一个线程在执行


- 适用于有明确执行顺序但是不影响主线程的任务,压入池中的任务会按照队列顺序执行。


- 使用无界的LinkedBlockingQueue,要综合考虑生成与消费能力,生成过剩,可能导致堆内存溢出。

源码地址:https://github.com/qjm201000/concurrent_executorService.git

并发编程-concurrent指南-线程池ExecutorService的实例的更多相关文章

  1. 并发编程-concurrent指南-线程池ExecutorService的使用

    有几种不同的方式来将任务委托给 ExecutorService 去执行: execute(Runnable) submit(Runnable) submit(Callable) invokeAny(… ...

  2. Java并发编程:Java线程池核心ThreadPoolExecutor的使用和原理分析

    目录 引出线程池 Executor框架 ThreadPoolExecutor详解 构造函数 重要的变量 线程池执行流程 任务队列workQueue 任务拒绝策略 线程池的关闭 ThreadPoolEx ...

  3. Java并发编程:Java线程池

    转载自:http://www.cnblogs.com/dolphin0520/p/3932921.html 在前面的文章中,我们使用线程的时候就去创建一个线程,这样实现起来非常简便,但是就会有一个问题 ...

  4. 【Java并发编程六】线程池

    一.概述 在执行并发任务时,我们可以把任务传递给一个线程池,来替代为每个并发执行的任务都启动一个新的线程,只要池里有空闲的线程,任务就会分配一个线程执行.在线程池的内部,任务被插入一个阻塞队列(Blo ...

  5. 并发编程-concurrent指南-原子操作类-AtomicInteger

    在java并发编程中,会出现++,--等操作,但是这些不是原子性操作,这在线程安全上面就会出现相应的问题.因此java提供了相应类的原子性操作类. 1.AtomicInteger

  6. day33_8_15 并发编程4,线程池与协程,io模型

    一.线程池 线程池是一个处理线程任务的集合,他是可以接受一定量的线程任务,并创建线程,处理该任务,处理结束后不会立刻关闭池子,会继续等待提交的任务,也就是他们的进程/线程号不会改变. 当线程池中的任务 ...

  7. 并发编程 --进、线程池、协程、IO模型

    内容目录: 1.socket服务端实现并发 2.进程池,线程池 3.协程 4.IO模型 1.socket服务端实现并发 # 客户端: import socket client = socket.soc ...

  8. Java并发编程 (九) 线程调度-线程池

    个人博客网:https://wushaopei.github.io/    (你想要这里多有) 声明:实际上,在开发中并不会普遍的使用Thread,因为它具有一些弊端,对并发性能的影响比较大,如下: ...

  9. 并发编程-concurrent指南-Lock-可重入锁(ReentrantLock)

    可重入和不可重入的概念是这样的:当一个线程获得了当前实例的锁,并进入方法A,这个线程在没有释放这把锁的时候,能否再次进入方法A呢? 可重入锁:可以再次进入方法A,就是说在释放锁前此线程可以再次进入方法 ...

随机推荐

  1. youwuku和koudaitong以及weimeng差异

    优库通过涨势没有口袋,通过口袋里的东西优库有, 就像一个商场的处理这些极端类别似, 所不同的是:1.掌上通免费,但也开始掏腰包通过用户收费,因为一些特殊的.这意味着,天下没有免费的午餐,掌上通是使用完 ...

  2. 在Winform窗体中使用WPF控件(附源码)

    原文:在Winform窗体中使用WPF控件(附源码) 今天是礼拜6,下雨,没有外出,闲暇就写一篇博文讲下如何在Winform中使用WPF控件.原有是我在百度上搜索相关信息无果,遂干脆动手自己实现. W ...

  3. Delphi跨平台Socket通讯库

    盒子中的souledge大侠发布了新的Socket库,以下为原文: 我之前写过一个iocp的框架,放到googlecode上了. 由于当时的delphi版本尚无法跨平台,所以该框架只能运行在Windo ...

  4. SQLServer 不允许保存更改的解决办法

    启动SQL Server  Management Studio 工具菜单----选项----Designers(设计器)----阻止保存要求重新创建表的更改 取消勾选即可.

  5. win10 uwp 如何打包Nuget给其他人

    原文:win10 uwp 如何打包Nuget给其他人 本文告诉大家,如果自己有做一些好用的库,如何使用 Nuget 打包之后上传,分享给大家. 首先需要知道一些 Nuget 打包需要知道的,请看 wi ...

  6. GRPC 1.3.4 发布,Google 高性能 RPC 框架(Java C++ Go)

    GRPC 1.3.4 发布了,GRPC 是一个高性能.开源.通用的 RPC 框架,面向移动和 HTTP/2 设计,是由谷歌发布的首款基于 Protocol Buffers 的 RPC 框架. GRPC ...

  7. mysq练习(二)

    Mysql练习(二) 1. delete,drop,truncate 的区别? 可以参考这位的:  https://www.cnblogs.com/zhizhao/p/7825469.html 2. ...

  8. Unity推荐设置(HoloLens开发系列)

    本文翻译自:Recommended settings for Unity Unity提供了一系列默认选项,这些选项能够适用于所有平台的一般情况.但是,Unity同样为HoloLens提供了一些特殊行为 ...

  9. 从IntToHex()说起,栈/堆地址标准写法 good

    学习中的一些牢骚.栈/堆地址标准写法. 2017-02-12 • 杂谈 • 暂无评论 • 老衲 •浏览 226 次 我一直都在寻找各种业务功能的最简单写法,用减法的模式来开发软件.下面是我的写法,如果 ...

  10. Qt:正确判断文件、文件夹是否存在的方法

    一直对Qt的isFile.isDir.exists这几个方法感到混乱,不知道到底用哪个,网上搜了下资料,也是用这几个方法但是都没有对其深究,经过测试发现会存在问题,先看看下面的测试代码 { QFile ...