当前位置: 移动技术网 > IT编程>开发语言>Java > 在spring boot中使用java线程池ExecutorService的讲解

在spring boot中使用java线程池ExecutorService的讲解

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

做过人流能看出来吗,郭俊苹,李赫男

1. 认识java线程池

1.1 在什么情况下使用线程池?

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

1.2 使用线程池的好处:

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

1.3 线程池包括以下四个基本组成部分:

  • 1、线程池管理器(threadpool):用于创建并管理线程池,包括 创建线程池,销毁线程池,添加新任务;
  • 2、工作线程(poolworker):线程池中线程,在没有任务时处于等待状态,可以循环的执行任务;
  • 3、任务接口(task):每个任务必须实现的接口,以供工作线程调度任务的执行,它主要规定了任务的入口,任务执行完后的收尾工作,任务的执行状态等;
  • 4、任务队列(taskqueue):用于存放没有处理的任务。提供一种缓冲机制。

1.4 线程池的核心参数

threadpoolexecutor 有四个构造方法,前三个都是调用最后一个(最后一个参数最全)

 public threadpoolexecutor(int corepoolsize,
               int maximumpoolsize,
               long keepalivetime,
               timeunit unit,
               blockingqueue<runnable> workqueue) {
    this(corepoolsize, maximumpoolsize, keepalivetime, unit, workqueue,
       executors.defaultthreadfactory(), defaulthandler);
  }
  public threadpoolexecutor(int corepoolsize,
               int maximumpoolsize,
               long keepalivetime,
               timeunit unit,
               blockingqueue<runnable> workqueue,
               threadfactory threadfactory) {
    this(corepoolsize, maximumpoolsize, keepalivetime, unit, workqueue,
       threadfactory, defaulthandler);
  }
  public threadpoolexecutor(int corepoolsize,
               int maximumpoolsize,
               long keepalivetime,
               timeunit unit,
               blockingqueue<runnable> workqueue,
               rejectedexecutionhandler handler) {
    this(corepoolsize, maximumpoolsize, keepalivetime, unit, workqueue,
       executors.defaultthreadfactory(), handler);
  }
  // 都调用它
  public threadpoolexecutor(// 核心线程数
  int corepoolsize, 
               // 最大线程数
               int maximumpoolsize, 
               // 闲置线程存活时间
               long keepalivetime, 
               // 时间单位
               timeunit unit, 
               // 线程队列
               blockingqueue<runnable> workqueue, 
               // 线程工厂 
               threadfactory threadfactory,        
               // 队列已满,而且当前线程数已经超过最大线程数时的异常处理策略       
               rejectedexecutionhandler handler  ) {
    if (corepoolsize < 0 ||
      maximumpoolsize <= 0 ||
      maximumpoolsize < corepoolsize ||
      keepalivetime < 0)
      throw new illegalargumentexception();
    if (workqueue == null || threadfactory == null || handler == null)
      throw new nullpointerexception();
    this.corepoolsize = corepoolsize;
    this.maximumpoolsize = maximumpoolsize;
    this.workqueue = workqueue;
    this.keepalivetime = unit.tonanos(keepalivetime);
    this.threadfactory = threadfactory;
    this.handler = handler;
  }

主要参数

corepoolsize:核心线程数

  • 核心线程会一直存活,即使没有任务需要执行
  • 当线程数小于核心线程数时,即使有线程空闲,线程池也会优先创建新线程处理
  • 设置allowcorethreadtimeout=true(默认false)时,核心线程会超时关闭

maxpoolsize:最大线程数

  • 当线程数>=corepoolsize,且任务队列已满时。线程池会创建新线程来处理任务
  • 当线程数=maxpoolsize,且任务队列已满时,线程池会拒绝处理任务而抛出异常

keepalivetime:线程空闲时间

  • 当线程空闲时间达到keepalivetime时,线程会退出,直到线程数量=corepoolsize
  • 如果allowcorethreadtimeout=true,则会直到线程数量=0

workqueue:一个阻塞队列,用来存储等待执行的任务,这个参数的选择也很重要,会对线程池的运行过程产生重大影响,一般来说,这里的阻塞队列有以下几种选择:

  • arrayblockingqueue;
  • linkedblockingqueue;
  • synchronousqueue;

关于阻塞队列可以看这篇:

threadfactory:线程工厂,主要用来创建线程;

rejectedexecutionhandler:任务拒绝处理器,两种情况会拒绝处理任务:

  • 当线程数已经达到maxpoolsize,切队列已满,会拒绝新任务
  • 当线程池被调用shutdown()后,会等待线程池里的任务执行完毕,再shutdown。如果在调用shutdown()和线程池真正shutdown之间提交任务,会拒绝新任务

当拒绝处理任务时线程池会调用rejectedexecutionhandler来处理这个任务。如果没有设置默认是abortpolicy,会抛出异常。threadpoolexecutor类有几个内部实现类来处理这类情况:

  • abortpolicy 丢弃任务,抛运行时异常
  • callerrunspolicy 执行任务
  • discardpolicy 忽视,什么都不会发生
  • discardoldestpolicy 从队列中踢出最先进入队列(最后一个执行)的任务
  • 实现rejectedexecutionhandler接口,可自定义处理器

1.5 java线程池 executorservice

  • executors.newcachedthreadpool 创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。
  • executors.newfixedthreadpool 创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。
  • executors.newscheduledthreadpool 创建一个定长线程池,支持定时及周期性任务执行。
  • executors.newsinglethreadexecutor 创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(fifo, lifo, 优先级)执行。

备注:executors只是一个工厂类,它所有的方法返回的都是threadpoolexecutor、scheduledthreadpoolexecutor这两个类的实例。

1.6 executorservice有如下几个执行方法

  • executorservice.execute(runnable);这个方法接收一个runnable实例,并且异步的执行
  • executorservice.submit(runnable)
  • executorservice.submit(callable)
  • executorservice.invokeany(…)
  • executorservice.invokeall(…)

execute(runnable)

这个方法接收一个runnable实例,并且异步的执行

executorservice.execute(new runnable() {
public void run() {
  system.out.println("asynchronous task");
}
});
executorservice.shutdown();

submit(runnable)

submit(runnable)和execute(runnable)区别是前者可以返回一个future对象,通过返回的future对象,我们可以检查提交的任务是否执行完毕,请看下面执行的例子:

future future = executorservice.submit(new runnable() {
public void run() {
  system.out.println("asynchronous task");
}
});
future.get(); //returns null if the task has finished correctly.

submit(callable)

submit(callable)和submit(runnable)类似,也会返回一个future对象,但是除此之外,submit(callable)接收的是一个callable的实现,callable接口中的call()方法有一个返回值,可以返回任务的执行结果,而runnable接口中的run()方法是void的,没有返回值。请看下面实例:

future future = executorservice.submit(new callable(){
public object call() throws exception {
  system.out.println("asynchronous callable");
  return "callable result";
}
});
system.out.println("future.get() = " + future.get());

如果任务执行完成,future.get()方法会返回callable任务的执行结果。注意,future.get()方法会产生阻塞。

invokeany(…)

invokeany(…)方法接收的是一个callable的集合,执行这个方法不会返回future,但是会返回所有callable任务中其中一个任务的执行结果。这个方法也无法保证返回的是哪个任务的执行结果,反正是其中的某一个。

executorservice executorservice = executors.newsinglethreadexecutor();
set<callable<string>> callables = new hashset<callable<string>>();
callables.add(new callable<string>() {
public string call() throws exception {
  return "task 1";
}
});
callables.add(new callable<string>() {
public string call() throws exception {
  return "task 2";
}
});
callables.add(new callable<string>() {
  public string call() throws exception {
  return "task 3";
}
});
string result = executorservice.invokeany(callables);
system.out.println("result = " + result);
executorservice.shutdown();

invokeall(…)

invokeall(…)与 invokeany(…)类似也是接收一个callable集合,但是前者执行之后会返回一个future的list,其中对应着每个callable任务执行后的future对象。

list<future<string>> futures = executorservice.invokeall(callables);
for(future<string> future : futures){
system.out.println("future.get = " + future.get());
}
executorservice.shutdown();

2. 在springboot中使用java线程池executorservice

2.1 springboot 的使用配置

import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;
import java.util.concurrent.executorservice;
import java.util.concurrent.executors;
/**
 * 数据收集配置,主要作用在于spring启动时自动加载一个executorservice对象.
 * @author bruce
 * @date 2017/2/22
 * update by cliff at 2027/11/03
 */
@configuration
public class threadpoolconfig {
  @bean
  public executorservice getthreadpool(){
    return executors.newfixedthreadpool();
  }
}

2.2 使用

在@service 中注入 executorservice 然后就可以直接用了。
  @autowired
  private executorservice executorservice;
public void test(){
    executorservice.execute(new runnable() {
      public void run() {
        system.out.println("asynchronous task");
      }
    });
  }

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对移动技术网的支持。如果你想了解更多相关内容请查看下面相关链接

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网