当前位置: 移动技术网 > IT编程>开发语言>Java > Java 线程池ExecutorService详解及实例代码

Java 线程池ExecutorService详解及实例代码

2019年07月22日  | 移动技术网IT编程  | 我要评论

java 线程池executorservice

1.线程池 

1.1什么情况下使用线程池

  1. 单个任务处理的时间比较短.
  2. 将需处理的任务的数量大.

1.2使用线程池的好处

  1. 减少在创建和销毁线程上所花的时间以及系统资源的开销.
  2. 如果不使用线程池,有可能造成系统创建大量线程而导致消耗系统内存以及”过度切换”;

2.executorservice和executors

2.1简介

executorservice是一个接口,继承了executor,

public interface executorservice extend executor{
}

executor也是一个接口,该接口只包含一个方法:

public interface executor {
  void execute(runnable command);
}

java里面的线程池的顶级接口是excutor,但是严格意义上来说>>exector并不是一个线程池,而只是一个执行线程的工具,真正的线程>池接口是executorservice.

3.executors

它是一个静态工厂类,它能生产不同类型的线程池,部分源码如下:

public class executors {
//newfixedthreadpool
public static executorservice newfixedthreadpool(int nthreads) {
    return new threadpoolexecutor(nthreads, nthreads, 0l, timeunit.milliseconds,new linkedblockingqueue<runnable>());
}
//newcachethreadpool
 public static executorservice newcachedthreadpool() {
    return new threadpoolexecutor(0, integer.max_value,60l, timeunit.seconds,new synchronousqueue<runnable>());
  }
 //newscheduledthreadpool
  public static scheduledexecutorservice newscheduledthreadpool(int corepoolsize) {
    return new scheduledthreadpoolexecutor(corepoolsize);
  }
  //newstringooo
}

先看一个具体的例子,用例子来说明它们之间的异同.

package thread;
import java.util.concurrent.executorservice;
import java.util.concurrent.executors;
import java.util.concurrent.scheduledexecutorservice;

/**
 * created by yang on 16-7-11.
 */
public class ch09_executor {
  private static void run(executorservice threadpool) {
    for (int i = 1; i < 5; i++) {
      final int taskid=i;
      threadpool.execute(new runnable() {
        @override
        public void run() {
          for(int i=1;i<5;i++){
            try{
              thread.sleep(20);
            }catch (interruptedexception e)
            {
              e.printstacktrace();
            }
            system.out.println("第"+taskid+"次任务的第"+i+"次执行");
          }
        }
      });
    }
    threadpool.shutdown();

  }

  public static void main(string[] args) {
    //创建可以容纳3个线程的线程池
    executorservice fixedthreadpool= executors.newfixedthreadpool(3);
    //线程池的大小会根据执行的任务动态的分配
    executorservice cachethreadpool=executors.newcachedthreadpool();
    //创建单个线程的线程池,如果当前线程在执行任务时突然中断,则会创建一个新的线程替换它继续执行.
    executorservice singlethreadpool=executors.newsinglethreadexecutor();
    //效果类似于timer定时器
    scheduledexecutorservice scheduledthreadpool=executors.newscheduledthreadpool(3);
    // run(fixedthreadpool); //(1)
    //run(cachethreadpool); //(2)
    // run(singlethreadpool); //(3)
    // run(scheduledthreadpool); //(4)
  }
}

4. 4种常用的线程池

4.1 cachedthreadpool

cachedthreadpool会创建一个缓存区,将初始化的线程缓存起来,会终止并且从缓存中移除已有6秒未被使用的线程.
如果线程有可用,就使用之前创建好的线程.如果线程没有可用的,就新创建线程.

.重用:

缓存型池子,先看看池中有没有以前建立的线程,如果有,就reuse,如果没有,就新建一个新的线程加入池中,

使用场景:

缓存型池子通常用于执行一些生存期很短的异步型任务,因此在一些面向连接的daemon型server中用地不多.

超时:

能reuse的线程,必须是timeout idle内的池中线程,缺省timeout是60s,超过这个idle时长,线程实例将被终止及移除池.

结束:

放入cachedthreadpool的线程不必担心其结束,超过timeout不活动,其会被自动终止.

实例解说:

去掉(2)的注释,运行,得到的运行结果如下:

第1次任务的第1次执行
第3次任务的第1次执行
第2次任务的第1次执行
第4次任务的第1次执行
第3次任务的第2次执行
第1次任务的第2次执行
第2次任务的第2次执行
第4次任务的第2次执行
第3次任务的第3次执行
第1次任务的第3次执行
第2次任务的第3次执行
第4次任务的第3次执行
第3次任务的第4次执行
第2次任务的第4次执行
第4次任务的第4次执行
第1次任务的第4次执行

从结果可以看出,4个任务是交替执行的.

4.2fixedthreadpool

在fixedthreadpool中,有一个固定大小的池,

如果当前需要执行的任务超过池大小,那么多出去的任务处于等待状态,直到有空闲下来的线程执行任务。
如果当前需要执行的任务小于池大小,空闲线程不会被销毁.

重用:

fixedthreadpool与cachethreadpool差不多,也是能reuse就用,但不能随时建新的线程

固定数目

其独特之处在于,任意时间点,最多只能有固定数目的活动线程存在,此时如果有新的线程要建立,只能放在另外的队列中等待,直到当前的线程中某个线程终止直接被移出池子

超时:

和cachethreadpool不同,fixedthreadpool没有idle机制

使用场景:

所以fixedthreadpool多数针对一些很稳定很固定的正规并发线程,多用于服务器

源码分析:

从方法的源代码看,cache池和fixed 池调用的是同一个底层池,只不过参数不同.
fixed池线程数固定,并且是0秒idle(无idle)
cache池线程数支持0-integer.max_value(显然完全没考虑主机的资源承受能力),60秒idle

实例解说:

去掉(1)的注释,运行结果如下:

第1次任务的第1次执行
第3次任务的第1次执行
第2次任务的第1次执行
第1次任务的第2次执行
第3次任务的第2次执行
第2次任务的第2次执行
第1次任务的第3次执行
第3次任务的第3次执行
第2次任务的第3次执行
第1次任务的第4次执行
第3次任务的第4次执行
第2次任务的第4次执行
第4次任务的第1次执行
第4次任务的第2次执行
第4次任务的第3次执行
第4次任务的第4次执行

创建了一个固定大小的线程池,容量是为3,然后循环执行4个任务,由输出结果可以看出,前3个任务首先执行完,然后空闲下来的线程去执行第4个任务.

4.3singlethreadexecutor

  1. singlethreadexector得到的是一个单个线程,这个线程会保证你的任务执行完成.
  2. 单例线程,任意时间池中只能有一个线程
  3. 如果当前线程意外终止,会创建一个新的线程继续执行任务,这和我们直接创建线程不同,也和newfixedthreadpool(1)不同.
  4. 用的是和cache池和fixed池相同的底层池,但线程数目是1-1,0秒idle(无idle)

去掉(3)注释. 看执行结果如下:

第1次任务的第1次执行
第1次任务的第2次执行
第1次任务的第3次执行
第1次任务的第4次执行
第2次任务的第1次执行
第2次任务的第2次执行
第2次任务的第3次执行
第2次任务的第4次执行
第3次任务的第1次执行
第3次任务的第2次执行
第3次任务的第3次执行
第3次任务的第4次执行
第4次任务的第1次执行
第4次任务的第2次执行
第4次任务的第3次执行
第4次任务的第4次执行

四个任务是顺序执行的.

4.4 scheduledthreadpool

scheduledthreadpool是一个固定大小的线程池,与fixedthreadpool类似,执行的任务是定时任务.
去掉(4)的注释得到的结果和fixedthreadpool得到的结果相同,scheduledthreadpool的主要没有在这里,而是定时任务,看下面这个例子:

package thread;
import java.util.concurrent.executors;
import java.util.concurrent.scheduledexecutorservice;
import java.util.concurrent.timeunit;

/**
 * created by yang on 16-7-11.
 */
public class myscheduledtask implements runnable {
  private string tname;
  public myscheduledtask(string name){
    this.tname=name;
  }
  public void run(){
    system.out.println(tname+"任务时延时2秒执行!");
  }

  public static void main(string[] args) {
    scheduledexecutorservice scheduledpool= executors.newscheduledthreadpool(2);
    scheduledexecutorservice singschedulepool=executors.newsinglethreadscheduledexecutor();
    myscheduledtask mt1=new myscheduledtask("mt1");
    myscheduledtask mt2=new myscheduledtask("mt2");
    //以scheduledthreadpool启动mt1任务执行
    scheduledpool.schedule(mt1,2, timeunit.seconds);
    //用singlescheduledthreadpool启动mt2;
    singschedulepool.schedule(mt2,2000,timeunit.milliseconds);
    scheduledpool.shutdown();
    singschedulepool.shutdown();
  }
}

结果:

mt1任务时延时2秒执行!
mt2任务时延时2秒执行!

在程序运行2秒后,才会有结果显示,说明线程在2秒后执行的.

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网