欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Spring boot多线程配置方法

程序员文章站 2024-02-17 10:14:34
本文实例为大家分享了spring boot多线程配置的具体代码,供大家参考,具体内容如下 1、配置线程配置类 package test; import j...

本文实例为大家分享了spring boot多线程配置的具体代码,供大家参考,具体内容如下

1、配置线程配置类

package test;

import java.util.concurrent.executor;

import org.springframework.aop.interceptor.asyncuncaughtexceptionhandler;
import org.springframework.context.annotation.componentscan;
import org.springframework.context.annotation.configuration;
import org.springframework.scheduling.annotation.asyncconfigurer;
import org.springframework.scheduling.annotation.enableasync;
import org.springframework.scheduling.concurrent.threadpooltaskexecutor;

@configuration
@componentscan("test")
@enableasync
// 线程配置类
public class asynctaskconfig implements asyncconfigurer {

  // thredpooltaskexcutor的处理流程
  // 当池子大小小于corepoolsize,就新建线程,并处理请求
  // 当池子大小等于corepoolsize,把请求放入workqueue中,池子里的空闲线程就去workqueue中取任务并处理
  // 当workqueue放不下任务时,就新建线程入池,并处理请求,如果池子大小撑到了maximumpoolsize,就用rejectedexecutionhandler来做拒绝处理
  // 当池子的线程数大于corepoolsize时,多余的线程会等待keepalivetime长时间,如果无请求可处理就自行销毁

  @override
  public executor getasyncexecutor() {
    threadpooltaskexecutor taskexecutor = new threadpooltaskexecutor();
    taskexecutor.setcorepoolsize(5);// 最小线程数
    taskexecutor.setmaxpoolsize(10);// 最大线程数
    taskexecutor.setqueuecapacity(25);// 等待队列

    taskexecutor.initialize();

    return taskexecutor;
  }

  @override
  public asyncuncaughtexceptionhandler getasyncuncaughtexceptionhandler() {
    return null;
  }
}

2、定义线程执行任务类

package test;

import java.util.random;
import java.util.concurrent.future;

import org.springframework.scheduling.annotation.async;
import org.springframework.scheduling.annotation.asyncresult;
import org.springframework.stereotype.service;

@service
// 线程执行任务类
public class asynctaskservice {

  random random = new random();// 默认构造方法

  @async
  // 表明是异步方法
  // 无返回值
  public void executeasynctask(integer i) {
    system.out.println("执行异步任务:" + i);
  }

  /**
   * 异常调用返回future
   * 
   * @param i
   * @return
   * @throws interruptedexception
   */
  @async
  public future<string> asyncinvokereturnfuture(int i) throws interruptedexception {
    system.out.println("input is " + i);
    thread.sleep(1000 * random.nextint(i));

    future<string> future = new asyncresult<string>("success:" + i);// future接收返回值,这里是string类型,可以指明其他类型

    return future;
  }
}

3、调用

package test;

import java.util.arraylist;
import java.util.list;
import java.util.concurrent.executionexception;
import java.util.concurrent.future;

import org.springframework.context.annotation.annotationconfigapplicationcontext;
import org.springframework.core.task.taskrejectedexception;

public class application {

  public static void main(string[] args) throws interruptedexception, executionexception {
    // testvoid();

    testreturn();
  }

  // 测试无返回结果
  private static void testvoid() {
    annotationconfigapplicationcontext context = new annotationconfigapplicationcontext(asynctaskconfig.class);
    asynctaskservice asynctaskservice = context.getbean(asynctaskservice.class);

    // 创建了20个线程
    for (int i = 1; i <= 20; i++) {
      asynctaskservice.executeasynctask(i);
    }

    context.close();
  }

  // 测试有返回结果
  private static void testreturn() throws interruptedexception, executionexception {
    annotationconfigapplicationcontext context = new annotationconfigapplicationcontext(asynctaskconfig.class);
    asynctaskservice asynctaskservice = context.getbean(asynctaskservice.class);

    list<future<string>> lstfuture = new arraylist<future<string>>();// 存放所有的线程,用于获取结果

    // 创建100个线程
    for (int i = 1; i <= 100; i++) {
      while (true) {
        try {
          // 线程池超过最大线程数时,会抛出taskrejectedexception,则等待1s,直到不抛出异常为止
          future<string> future = asynctaskservice.asyncinvokereturnfuture(i);
          lstfuture.add(future);

          break;
        } catch (taskrejectedexception e) {
          system.out.println("线程池满,等待1s。");
          thread.sleep(1000);
        }
      }
    }

    // 获取值。get是阻塞式,等待当前线程完成才返回值
    for (future<string> future : lstfuture) {
      system.out.println(future.get());
    }

    context.close();
  }
}

maven配置

<project xmlns="http://maven.apache.org/pom/4.0.0" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation="http://maven.apache.org/pom/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelversion>4.0.0</modelversion>
 <groupid>testaysc</groupid>
 <artifactid>testaysc</artifactid>
 <version>0.0.1-snapshot</version>
 <dependencies>
   <dependency>
     <groupid>org.springframework.boot</groupid>
     <artifactid>spring-boot</artifactid>
     <version>1.5.6.release</version>
   </dependency>
   <dependency>
     <groupid>org.springframework</groupid>
     <artifactid>spring-aop</artifactid>
     <version>4.3.10.release</version>
   </dependency>
 </dependencies>
</project>

结果展示:

1、无返回结果

Spring boot多线程配置方法

2、有返回结果

Spring boot多线程配置方法

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。