zoukankan      html  css  js  c++  java
  • Spring boot多线程

    1、配置线程配置类

     1 package test;
     2 
     3 import java.util.concurrent.Executor;
     4 
     5 import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
     6 import org.springframework.context.annotation.ComponentScan;
     7 import org.springframework.context.annotation.Configuration;
     8 import org.springframework.scheduling.annotation.AsyncConfigurer;
     9 import org.springframework.scheduling.annotation.EnableAsync;
    10 import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
    11 
    12 @Configuration
    13 @ComponentScan("test")
    14 @EnableAsync
    15 // 线程配置类
    16 public class AsyncTaskConfig implements AsyncConfigurer {
    17 
    18     // ThredPoolTaskExcutor的处理流程
    19     // 当池子大小小于corePoolSize,就新建线程,并处理请求
    20     // 当池子大小等于corePoolSize,把请求放入workQueue中,池子里的空闲线程就去workQueue中取任务并处理
    21     // 当workQueue放不下任务时,就新建线程入池,并处理请求,如果池子大小撑到了maximumPoolSize,就用RejectedExecutionHandler来做拒绝处理
    22     // 当池子的线程数大于corePoolSize时,多余的线程会等待keepAliveTime长时间,如果无请求可处理就自行销毁
    23 
    24     @Override
    25     public Executor getAsyncExecutor() {
    26         ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
    27         taskExecutor.setCorePoolSize(5);// 最小线程数
    28         taskExecutor.setMaxPoolSize(10);// 最大线程数
    29         taskExecutor.setQueueCapacity(25);// 等待队列
    30 
    31         taskExecutor.initialize();
    32 
    33         return taskExecutor;
    34     }
    35 
    36     @Override
    37     public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
    38         return null;
    39     }
    40 }

    2、定义线程执行任务类

     1 package test;
     2 
     3 import java.util.Random;
     4 import java.util.concurrent.Future;
     5 
     6 import org.springframework.scheduling.annotation.Async;
     7 import org.springframework.scheduling.annotation.AsyncResult;
     8 import org.springframework.stereotype.Service;
     9 
    10 @Service
    11 // 线程执行任务类
    12 public class AsyncTaskService {
    13 
    14     Random random = new Random();// 默认构造方法
    15 
    16     @Async
    17     // 表明是异步方法
    18     // 无返回值
    19     public void executeAsyncTask(Integer i) {
    20         System.out.println("执行异步任务:" + i);
    21     }
    22 
    23     /**
    24      * 异常调用返回Future
    25      * 
    26      * @param i
    27      * @return
    28      * @throws InterruptedException
    29      */
    30     @Async
    31     public Future<String> asyncInvokeReturnFuture(int i) throws InterruptedException {
    32         System.out.println("input is " + i);
    33         Thread.sleep(1000 * random.nextInt(i));
    34 
    35         Future<String> future = new AsyncResult<String>("success:" + i);// Future接收返回值,这里是String类型,可以指明其他类型
    36 
    37         return future;
    38     }
    39 }

    3、调用

     1 package test;
     2 
     3 import java.util.ArrayList;
     4 import java.util.List;
     5 import java.util.concurrent.ExecutionException;
     6 import java.util.concurrent.Future;
     7 
     8 import org.springframework.context.annotation.AnnotationConfigApplicationContext;
     9 import org.springframework.core.task.TaskRejectedException;
    10 
    11 public class Application {
    12 
    13     public static void main(String[] args) throws InterruptedException, ExecutionException {
    14         // testVoid();
    15 
    16         testReturn();
    17     }
    18 
    19     // 测试无返回结果
    20     private static void testVoid() {
    21         AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AsyncTaskConfig.class);
    22         AsyncTaskService asyncTaskService = context.getBean(AsyncTaskService.class);
    23 
    24         // 创建了20个线程
    25         for (int i = 1; i <= 20; i++) {
    26             asyncTaskService.executeAsyncTask(i);
    27         }
    28 
    29         context.close();
    30     }
    31 
    32     // 测试有返回结果
    33     private static void testReturn() throws InterruptedException, ExecutionException {
    34         AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AsyncTaskConfig.class);
    35         AsyncTaskService asyncTaskService = context.getBean(AsyncTaskService.class);
    36 
    37         List<Future<String>> lstFuture = new ArrayList<Future<String>>();// 存放所有的线程,用于获取结果
    38 
    39         // 创建100个线程
    40         for (int i = 1; i <= 100; i++) {
    41             while (true) {
    42                 try {
    43                     // 线程池超过最大线程数时,会抛出TaskRejectedException,则等待1s,直到不抛出异常为止
    44                     Future<String> future = asyncTaskService.asyncInvokeReturnFuture(i);
    45                     lstFuture.add(future);
    46 
    47                     break;
    48                 } catch (TaskRejectedException e) {
    49                     System.out.println("线程池满,等待1S。");
    50                     Thread.sleep(1000);
    51                 }
    52             }
    53         }
    54 
    55         // 获取值。get是阻塞式,等待当前线程完成才返回值
    56         for (Future<String> future : lstFuture) {
    57             System.out.println(future.get());
    58         }
    59 
    60         context.close();
    61     }
    62 }

    maven配置

     1 <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">
     2   <modelVersion>4.0.0</modelVersion>
     3   <groupId>TestAysc</groupId>
     4   <artifactId>TestAysc</artifactId>
     5   <version>0.0.1-SNAPSHOT</version>
     6   <dependencies>
     7       <dependency>
     8           <groupId>org.springframework.boot</groupId>
     9           <artifactId>spring-boot</artifactId>
    10           <version>1.5.6.RELEASE</version>
    11       </dependency>
    12       <dependency>
    13           <groupId>org.springframework</groupId>
    14           <artifactId>spring-aop</artifactId>
    15           <version>4.3.10.RELEASE</version>
    16       </dependency>
    17   </dependencies>
    18 </project>

     结果展示:

    1、无返回结果

    2、有返回结果

  • 相关阅读:
    sql 事务
    GridView数据导入Excel
    图片对比度亮度调节函数
    在.NET(C#)中获取电脑名IP地址及当前用户名
    一个简单的存储过程
    通用海量数据库翻页
    Graphics
    sql 触发器
    DataTable中的数据导出Excel文件
    窗口渐变
  • 原文地址:https://www.cnblogs.com/leanfish/p/7754147.html
Copyright © 2011-2022 走看看