ExecutorService与ThreadPoolTaskExecutor

Posted liduanwen

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ExecutorService与ThreadPoolTaskExecutor相关的知识,希望对你有一定的参考价值。

1.ExecutorService 

private static ExecutorService exec = null;
public static ExecutorService getExecutorServiceInstance(){
if(exec == null){
exec = Executors.newCachedThreadPool();
}
return exec;
}
public void threadNoticeOrMessageOrShortMessage (Integer type, Map<String, String> map, List<String> replaceParameter, List<String> list, Integer saveFlag){
exec = getExecutorServiceInstance();
NoticeOrMessageOrShortMessage noticeOrMessageOrShortMessage = new NoticeOrMessageOrShortMessage(getMessagePushInstance(), type, map, replaceParameter, list, saveFlag,
messagePushService, sendPushService, sendSmsService, sendMessageService);
exec.execute(noticeOrMessageOrShortMessage);
}

2.ThreadPoolTaskExecutor

<bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
<property name="corePoolSize" value="${task.core_pool_size}" />
<property name="maxPoolSize" value="${task.max_pool_size}" />
<property name="queueCapacity" value="${task.queue_capacity}" />
<property name="keepAliveSeconds" value="${task.keep_alive_seconds}" />
  <!-- 新增 -->
  1. <!-- 线程池对拒绝任务(无线程可用)的处理策略 -->  
  2.     <property name="rejectedExecutionHandler">  
  3.       <bean class="java.util.concurrent.ThreadPoolExecutor$CallerRunsPolicy" />  
  4.     </property>  

</bean>

@Resource(name = "taskExecutor")
private TaskExecutor taskExecutor;
private void addSendTask(final MimeMessage mimeMessage) {
try {
taskExecutor.execute(new Runnable() {
public void run() {
javaMailSender.send(mimeMessage);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
另外一种方式(未验证代码准确性)
private static ThreadPoolTaskExecutor threadPoolTaskExecutor = null;
public static ThreadPoolTaskExecutor getThreadPoolTaskExecutor Instance(){
    if(threadPoolTaskExecutor == null){
    threadPoolTaskExecutor.setCorePoolSize(5);
    threadPoolTaskExecutor.setMaxPoolSize(50);
    threadPoolTaskExecutor.setQueueCapacity(1000);
    threadPoolTaskExecutor.setKeepAliveSeconds(60);
    try {
  taskExecutor.execute(new Runnable() {
   public void run() {
  javaMailSender.send(mimeMessage);
  }
  });
  } catch (Exception e) {
e.printStackTrace();
  }
   }
    return exec;
}

具体线程还是有些不懂

以上是关于ExecutorService与ThreadPoolTaskExecutor的主要内容,如果未能解决你的问题,请参考以下文章

Java多线程ExecutorService与ExecutorCompletionService

ExecutorService与ThreadPoolTaskExecutor

ExecutorService.submit()与Executor.execute()的区别

线程池ExecutorService与quartz搭配出现的问题

使用 ExecutorService 有啥好处?

java多线程之Executor 与 ExecutorService两个基本接口