1.newCachedThreadPool() | -缓存型池子,先查看池中有没有以前建立的线程,如果有,就reuse.如果没有,就建一个新的线程加入池中 -缓存型池子通常用于执行一些生存期很短的异步型任务 因此在一些面向连接的daemon型SERVER中用得不多。 -能reuse的线程,必须是timeout IDLE内的池中线程,缺省timeout是60s,超过这个IDLE时长,线程实例将被终止及移出池。 注意,放入CachedThreadPool的线程不必担心其结束,超过TIMEOUT不活动,其会自动被终止。 |
2.newFixedThreadPool | -newFixedThreadPool与cacheThreadPool差不多,也是能reuse就用,但不能随时建新的线程 -其独特之处:任意时间点,最多只能有固定数目的活动线程存在,此时如果有新的线程要建立,只能放在另外的队列中等待,直到当前的线程中某个线程终止直接被移出池子 -和cacheThreadPool不同,FixedThreadPool没有IDLE机制(可能也有,但既然文档没提,肯定非常长,类似依赖上层的TCP或UDP IDLE机制之类的),所以FixedThreadPool多数针对一些很稳定很固定的正规并发线程,多用于服务器 -从方法的源代码看,cache池和fixed 池调用的是同一个底层池,只不过参数不同: fixed池线程数固定,并且是0秒IDLE(无IDLE) cache池线程数支持0-Integer.MAX_VALUE(显然完全没考虑主机的资源承受能力),60秒IDLE |
3.ScheduledThreadPool | -调度型线程池 -这个池子里的线程可以按schedule依次delay执行,或周期执行 |
4.SingleThreadExecutor | -单例线程,任意时间池中只能有一个线程 -用的是和cache池和fixed池相同的底层池,但线程数目是1-1,0秒IDLE(无IDLE) |
1.CachedThreadPool
CachedThreadPool首先会按照需要创建足够多的线程来执行任务(Task)。随着程序执行的过程,有的线程执行完了任务,可以被重新循环使用时,才不再创建新的线程来执行任务。我们采用《Thinking In Java》中的例子来分析。客户端线程和线程池之间会有一个任务队列。当程序要关闭时,你需要注意两件事情:入队的这些任务的情况怎么样了以及正在运行的这个任务执行得如 何了。令人惊讶的是很多开发人员并没能正确地或者有意识地去关闭线程池。正确的方法有两种:一个是让所有的入队任务都执行完毕(shutdown()), 再就是舍弃这些任务(shutdownNow())——这完全取决于你。比如说如果我们提交了N多任务并且希望等它们都执行完后才返回的话,那么就使用 shutdown():
public class ThreadPool implements Runnable {
private String threadName;
public ThreadPool() {
}
public ThreadPool(String threadName) {
this.threadName = threadName;
}
public String dateToString(Date date) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
return sdf.format(date);
}
/**
* 线程休眠一秒
*/
public void processCommand() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public void run() {
System.out.println(threadName + "-----开始时间:" + dateToString(new Date()));
processCommand();
System.out.println(threadName + "-----结束时间:" + dateToString(new Date()));
}
@Override
public String toString() {
return "ThreadPool{" +
"threadName='" + threadName + '\'' +
'}';
}
}
测试
/**
* 1.newCachedThreadPool
*/
public static void testCachedThreadPool() {
ThreadPool thread = new ThreadPool();
System.out.println("-----main开始时间:" + thread.dateToString(new Date()));
//创建一个缓冲池,缓冲池容量大小为Integer.MAX_VALUE
ExecutorService executorService = Executors.newCachedThreadPool();
for (int i = 0; i < 10; i++) {
executorService.execute(new ThreadPool(String.valueOf(i)));
}
//执行到此处不会马上关闭线程池,但之后不能再往线程池中加线程,否则会报错
executorService.shutdown();
System.out.println("-----main结束时间:" + thread.dateToString(new Date()));
}
运行结果:
从上面的结果可以看出:
1、主线程的执行与线程池里的线程分开,有可能主线程结束了,但是线程池还在运行
2、放入线程池的线程并不一定会按其放入的先后而顺序执行
2.FixedThreadPool
FixedThreadPool模式会使用一个优先固定数目的线程来处理若干数目的任务。规定数目的线程处理所有任务,一旦有线程处理完了任务就会被用来处理新的任务(如果有的话)。这种模式与上面的CachedThreadPool是不同的,CachedThreadPool模式下处理一定数量的任务的线程数目是不确定的。而FixedThreadPool模式下最多 的线程数目是一定的。
实例:
/**
* 2.newFixedThreadPool
*/
public static void testFixedThreadPool() {
ThreadPool thread = new ThreadPool();
System.out.println("-----main开始时间:" + thread.dateToString(new Date()));
//创建一个缓冲池,缓冲池容量大小为5
ExecutorService executorService = Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; i++) {
executorService.execute(new ThreadPool(String.valueOf(i)));
}
//执行到此处不会马上关闭线程池,但之后不能再往线程池中加线程,否则会报错
executorService.shutdown();
System.out.println("-----main结束时间:" + thread.dateToString(new Date()));
}
运行结果:
上面创建了一个固定大小的线程池,大小为5.也就说同一时刻最多只有5个线程能运行。并且线程执行完成后就从线程池中移出。它也不能保证放入的线程能按顺序执行。这要看在等待运行的线程的竞争状态了。
3、newSingleThreadExecutor
其实这个就是创建只能运行一条线程的线程池。它能保证线程的先后顺序执行,并且能保证一条线程执行完成后才开启另一条新的线程
/**
* 3.newSingleThreadExecutor:每次只开辟一个线程,保证线程执行完毕,再开启另一条线程
*/
public static void testSingleThreadPool() {
ThreadPool thread = new ThreadPool();
System.out.println("-----main开始时间:" + thread.dateToString(new Date()));
//创建一个缓冲池,缓冲池容量大小为1
ExecutorService executorService = Executors.newSingleThreadExecutor();
for (int i = 0; i < 10; i++) {
executorService.execute(new ThreadPool(String.valueOf(i)));
}
//执行到此处不会马上关闭线程池,但之后不能再往线程池中加线程,否则会报错
executorService.shutdown();
System.out.println("-----main结束时间:" + thread.dateToString(new Date()));
}
运行结果:
等价于newFixedThreadPool(1)
4、newScheduledThreadPool
这是一个计划线程池类,它能设置线程执行的先后间隔及执行时间等,功能比上面的三个强大了一些。
/**
* 4.newScheduledThreadPool
*/
public static void testScheduledThreadPool() {
ThreadPool thread = new ThreadPool();
System.out.println("-----main开始时间:" + thread.dateToString(new Date()));
//创建大小为10的线程
ScheduledThreadPoolExecutor exec = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(10);
for (int i = 0; i < 10; i++) {
//延迟10秒执行
exec.schedule(new ThreadPool(String.valueOf(i)),5,TimeUnit.SECONDS);
}
//执行到此处不会马上关闭线程池,但之后不能再往线程池中加线程,否则会报错
exec.shutdown();
//等待所有线程执行完毕
while(!exec.isTerminated()){
}
System.out.println("-----main结束时间:" + thread.dateToString(new Date()));
}
实现每个放入的线程延迟5秒执行。
运行结果如下:
ScheduledThreadPoolExecutor的定时方法主要有以下四种:
下面将主要来具体讲讲scheduleAtFixedRate和scheduleWithFixedDelay
scheduleAtFixedRate 按指定频率周期执行某个任务
public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
long initialDelay,
long period,
TimeUnit unit);
command:执行线程
initialDelay:初始化延时
period:两次开始执行最小间隔时间
unit:计时单位
scheduleWithFixedDelay 周期定时执行某个任务/按指定频率间隔执行某个任务(注意)
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
long initialDelay,
long delay,
TimeUnit unit);
command:执行线程
initialDelay:初始化延时
period:前一次执行结束到下一次执行开始的间隔时间(间隔执行延迟时间)
unit:计时单位
使用实例:
- class MyHandle implements Runnable {
- @Override
- public void run() {
- System.out.println(System.currentTimeMillis());
- try {
- Thread.sleep(1 * 1000);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
1.按指定频率周期执行某个任务
下面实现每隔2秒执行一次,注意,如果上次的线程还没有执行完成,那么会阻塞下一个线程的执行。即使线程池设置得足够大。
- /**
- * 初始化延迟0ms开始执行,每隔2000ms重新执行一次任务
- * @author linbingwen
- * @since 2016年6月6日
- */
- public static void executeFixedRate() {
- ScheduledExecutorService executor = Executors.newScheduledThreadPool(10);
- executor.scheduleAtFixedRate(
- new MyHandle(),
- 0,
- 2000,
- TimeUnit.MILLISECONDS);
- }
间隔指的是连续两次任务开始执行的间隔。对于scheduleAtFixedRate方法,当执行任务的时间大于我们指定的间隔时间时,它并不会在指定间隔时开辟一个新的线程并发执行这个任务。而是等待该线程执行完毕。
2、按指定频率间隔执行某个任务
- /**
- * 以固定延迟时间进行执行
- * 本次任务执行完成后,需要延迟设定的延迟时间,才会执行新的任务
- */
- public static void executeFixedDelay() {
- ScheduledExecutorService executor = Executors.newScheduledThreadPool(10);
- executor.scheduleWithFixedDelay(
- new MyHandle(),
- 0,
- 2000,
- TimeUnit.MILLISECONDS);
- }
间隔指的是连续上次执行完成和下次开始执行之间的间隔。
3.周期定时执行某个任务
周期性的执行一个任务,可以使用下面方法设定每天在固定时间执行一次任务。
- /**
- * 每天晚上9点执行一次
- * 每天定时安排任务进行执行
- */
- public static void executeEightAtNightPerDay() {
- ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
- long oneDay = 24 * 60 * 60 * 1000;
- long initDelay = getTimeMillis("21:00:00") - System.currentTimeMillis();
- initDelay = initDelay > 0 ? initDelay : oneDay + initDelay;
- executor.scheduleAtFixedRate(
- new MyHandle(),
- initDelay,
- oneDay,
- TimeUnit.MILLISECONDS);
- }
- /**
- * 获取指定时间对应的毫秒数
- * @param time "HH:mm:ss"
- * @return
- */
- private static long getTimeMillis(String time) {
- try {
- DateFormat dateFormat = new SimpleDateFormat("yy-MM-dd HH:mm:ss");
- DateFormat dayFormat = new SimpleDateFormat("yy-MM-dd");
- Date curDate = dateFormat.parse(dayFormat.format(new Date()) + " " + time);
- return curDate.getTime();
- } catch (ParseException e) {
- e.printStackTrace();
- }
- return 0;
- }
转自: https://blog.youkuaiyun.com/evankaka/article/details/51489322