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. Ubuntu安装配置Qt 4.86环境

    安装 QT4.8.6库+QT Creator 2.4.1 下载地址公布 QT4.8.6库  http://mirrors.hustunique.com/qt/official_releases/qt/ ...

  2. POJ - 2991 Crane (段树+计算几何)

    Description ACM has bought a new crane (crane -- jeřáb) . The crane consists of n segments of variou ...

  3. 利用花生壳对windows server进行远程桌面

    花生壳内网穿透 http://service.oray.com/question/1824.html windows server "允许远程协助连接这台计算机" 需要在服务器管理 ...

  4. DB First EF中的存储过程、函数、视图

    视图约等于表(属性)存储过程变为方法,方法中调用存储过程 EF可以调用存储过程,DB First的流程是刷新模型,获取存储过程,调用参考:http://blog.csdn.net/sudazf/art ...

  5. WPF DatePicker默认显示当前日期,格式化为年月日

    原文:WPF DatePicker默认显示当前日期 WPF的日历选择控件默认为当前日期,共有两种方法,一种静态,一种动态. 静态的当然写在DatePicker控件的属性里了,动态的写在对应的cs文件里 ...

  6. WPF 数据模板的使用

    <Window x:Class="CollectionBinding.MainWindow"        xmlns="http://schemas.micros ...

  7. qt部分类释义

    如果测试错误,输出包含源码的警告信息 Q_ASSERT Qtime最后一次star()或restar()到现在的毫秒数 QTime::elapsed QMetaObject::invokeMethod ...

  8. MVC WebApi的两种访问方法

    //UserInfoController using ClassLibrary; using System;using System.Collections.Generic;using System. ...

  9. Win8 Metro(C#)数字图像处理--3.5图像形心计算

    原文:Win8 Metro(C#)数字图像处理--3.5图像形心计算 /// <summary> /// Get the center of the object in an image. ...

  10. SqlServer & Windows 可更新订阅立即更新启用分布式事务协调器(MSDTC)

    原文:SqlServer & Windows 可更新订阅立即更新启用分布式事务协调器(MSDTC) 在可更新订阅中,在订阅设置更新方法,将 "排队更新" 设置为 " ...