使用场景:

方法处理到某一步,需要将信息交给另一个线程去处理!!

===================================================================================

第一种:最简单的Runnable

    public void test(String msg){
System.out.println(Thread.currentThread().getName()+":"+msg);
Runnable runnable = dealMsg(msg);
    //将返回的runnable对象传入,并start()启动线程
     new Thread(runnable).start();
}
//创建一个Runnable,重写run方法
public Runnable dealMsg(String msg){
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println("新开线程中处理:"+msg);
}
}; return runnable;
}

====================================================================================================

第二种:自己创建JDK线程池,交给spring管理,然后将任务交给线程池即可

1.创建线程池,交给spring管理

package com.sxd.util;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; @Configuration
public class ThreadConfig { /**
*newFixedThreadPool
创建一个指定工作线程数量的线程池。每当提交一个任务就创建一个工作线程,如果工作线程数量达到线程池初始的最大数,则将提交的任务存入到池队列中。 newCachedThreadPool
创建一个可缓存的线程池。这种类型的线程池特点是:
1).工作线程的创建数量几乎没有限制(其实也有限制的,数目为Interger. MAX_VALUE), 这样可灵活的往线程池中添加线程。
2).如果长时间没有往线程池中提交任务,即如果工作线程空闲了指定的时间(默认为1分钟),则该工作线程将自动终止。终止后,如果你又提交了新的任务,则线程池重新创建一个工作线程。 newSingleThreadExecutor
创建一个单线程化的Executor,即只创建唯一的工作者线程来执行任务,如果这个线程异常结束,会有另一个取代它,保证顺序执行(我觉得这点是它的特色)。单工作线程最大的特点是可保证顺序地执行各个任务,并且在任意给定的时间不会有多个线程是活动的 。 newScheduleThreadPool
创建一个定长的线程池,而且支持定时的以及周期性的任务执行,类似于Timer。
* @return
*/
@Bean
public ExecutorService getExecutorTools(){
ExecutorService executorService = Executors.newFixedThreadPool(8);
return executorService;
} }
package com.sxd.util;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; @Configuration
public class ThreadConfig { /**
*newFixedThreadPool
创建一个指定工作线程数量的线程池。每当提交一个任务就创建一个工作线程,如果工作线程数量达到线程池初始的最大数,则将提交的任务存入到池队列中。 newCachedThreadPool
创建一个可缓存的线程池。这种类型的线程池特点是:
1).工作线程的创建数量几乎没有限制(其实也有限制的,数目为Interger. MAX_VALUE), 这样可灵活的往线程池中添加线程。
2).如果长时间没有往线程池中提交任务,即如果工作线程空闲了指定的时间(默认为1分钟),则该工作线程将自动终止。终止后,如果你又提交了新的任务,则线程池重新创建一个工作线程。 newSingleThreadExecutor
创建一个单线程化的Executor,即只创建唯一的工作者线程来执行任务,如果这个线程异常结束,会有另一个取代它,保证顺序执行(我觉得这点是它的特色)。单工作线程最大的特点是可保证顺序地执行各个任务,并且在任意给定的时间不会有多个线程是活动的 。 newScheduleThreadPool
创建一个定长的线程池,而且支持定时的以及周期性的任务执行,类似于Timer。
* @return
*/
@Bean
public ExecutorService getExecutorTools(){
ExecutorService executorService = Executors.newFixedThreadPool(8);
return executorService;
} }

2.使用它

import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future; @Component
public class Consumer1 { @Resource
private ExecutorService executorService; public void test(String msg){
System.out.println(Thread.currentThread().getName()+":"+msg); /**
* 分类1:可以返回值的 Callable
*/
Future fal = executorService.submit(new Callable<String>() {
@Override
public String call() {
System.out.println(Thread.currentThread().getName()+":"+msg);
return "处理成功!";
}
}); try {
System.out.println(fal.get());
}catch (Exception e){
System.out.println(e);
} /**
* 分类2:不会返回值的 Runnable
*/
executorService.execute(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+":"+msg);
}
}); /**
* 分类3:也可以这样
*/
executorService.submit(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+":"+msg);
}
}); } }
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future; @Component
public class Consumer1 { @Resource
private ExecutorService executorService; public void test(String msg){
System.out.println(Thread.currentThread().getName()+":"+msg); /**
* 分类1:可以返回值的 Callable
*/
Future fal = executorService.submit(new Callable<String>() {
@Override
public String call() {
System.out.println(Thread.currentThread().getName()+":"+msg);
return "处理成功!";
}
}); try {
System.out.println(fal.get());
}catch (Exception e){
System.out.println(e);
} /**
* 分类2:不会返回值的 Runnable
*/
executorService.execute(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+":"+msg);
}
}); /**
* 分类3:也可以这样
*/
executorService.submit(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+":"+msg);
}
}); } }

====================================================================================================

第三种:使用spring封装的线程池

1.创建线程配置类【

@ComponentScan("com.sxd") 标明会在哪个包下使用多线程  

package com.sxd.util;

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("com.sxd")
@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;
}
}
package com.sxd.util;

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("com.sxd")
@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 com.sxd.util;

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(String msg) {
System.out.println(Thread.currentThread().getName()+"开启新线程执行" + msg);
} /**
* 异常调用返回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;
}
}
package com.sxd.util;

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(String msg) {
System.out.println(Thread.currentThread().getName()+"开启新线程执行" + msg);
} /**
* 异常调用返回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.使用它

@Component
public class Consumer1 { @Resource
private AsyncTaskService asyncTaskService; public void test(String msg){
System.out.println(Thread.currentThread().getName()+":"+msg); asyncTaskService.executeAsyncTask(msg); } }
@Component
public class Consumer1 { @Resource
private AsyncTaskService asyncTaskService; public void test(String msg){
System.out.println(Thread.currentThread().getName()+":"+msg); asyncTaskService.executeAsyncTask(msg); } }

====================================================================================================

第四种:在代码中启动异步处理最简单的代码

public void test(){
new Thread(()->doReplace(replaceLog)).start();
} public void doReplace(String replaceLog){ //异步处理的业务
}

======================================

就这么多,再补充噻!!

【spring boot】在spring boot下使用多线程的更多相关文章

  1. 【spring boot】13.在spring boot下使用多线程

    使用场景: 方法处理到某一步,需要将信息交给另一个线程去处理!! =================================================================== ...

  2. spring boot不要放在tomcat下启动,因为自身就带了集成tomcat

    spring boot不要放在tomcat下启动,因为自身就带了集成tomcat

  3. Spring Boot 获取 java resources 下文件

    Spring Boot 获取 java resources 下文件 Spring Boot 获取 resources 目录下的目录(例:获取 resources 目录下的 template 目录): ...

  4. 一:Spring Boot、Spring Cloud

    上次写了一篇文章叫Spring Cloud在国内中小型公司能用起来吗?介绍了Spring Cloud是否能在中小公司使用起来,这篇文章是它的姊妹篇.其实我们在这条路上已经走了一年多,从16年初到现在. ...

  5. Spring Kafka和Spring Boot整合实现消息发送与消费简单案例

    本文主要分享下Spring Boot和Spring Kafka如何配置整合,实现发送和接收来自Spring Kafka的消息. 先前我已经分享了Kafka的基本介绍与集群环境搭建方法.关于Kafka的 ...

  6. 使用Spring Session实现Spring Boot水平扩展

    小编说:本文使用Spring Session实现了Spring Boot水平扩展,每个Spring Boot应用与其他水平扩展的Spring Boot一样,都能处理用户请求.如果宕机,Nginx会将请 ...

  7. 一起来学spring Cloud | 第一章:spring Cloud 与Spring Boot

    目前大家都在说微服务,其实微服务不是一个名字,是一个架构的概念,大家现在使用的基于RPC框架(dubbo.thrift等)架构其实也能算作一种微服务架构. 目前越来越多的公司开始使用微服务架构,所以在 ...

  8. Spring,Spring MVC及Spring Boot区别

    什么是Spring?它解决了什么问题? 我们说到Spring,一般指代的是Spring Framework,它是一个开源的应用程序框架,提供了一个简易的开发方式,通过这种开发方式,将避免那些可能致使代 ...

  9. 基于Spring Boot、Spring Cloud、Docker的微服务系统架构实践

    由于最近公司业务需要,需要搭建基于Spring Cloud的微服务系统.遍访各大搜索引擎,发现国内资料少之又少,也难怪,国内Dubbo正统治着天下.但是,一个技术总有它的瓶颈,Dubbo也有它捉襟见肘 ...

随机推荐

  1. 打算安装个Ubuntu双系统,遇到了些基本概念问题(主分区、活动分区、扩展分区、逻辑分区)

    和运维的同事聊天,了解到: 1.XP系统时代(老的硬盘分区形式和分区表),最多允许建4个“主分区”,为了解决这个限制,就有了“扩展分区”的概念: 2.在“扩展分区”上,我们就可以建很多的“逻辑分区”, ...

  2. 基本的Bootstrap模板

    <!DOCTYPE html> <html> <html lang="zh-cn"> <meta charset="UTF-8& ...

  3. powerbuilder webbrowser 内嵌浏览器 select下拉框无法使用

        Windows Registry Editor Version 5.00 [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\MA ...

  4. [Android Memory] Android 的 StrictMode

    android的2.3 之后引入的StrictMode 对网络的访问做了限制啊. public void onCreate() { if (DEVELOPER_MODE) { StrictMode.s ...

  5. Android中关闭DatePicker和NumberPicker等Picker类的可编辑模式

    DatePicker.TimePicker.NumberPicker等控件在由于默认是可编辑的,所以会经常跳出键盘.要屏蔽这些编辑模式只需要如下代码: picker.setDescendantFocu ...

  6. 异常值监测的方法 Tukey test

    参考: https://www.zhihu.com/question/38066650

  7. HA分布式集群配置三 spark集群配置

    (一)HA下配置spark 1,spark版本型号:spark-2.1.0-bin-hadoop2.7 2,解压,修改配置环境变量 tar -zxvf spark-2.1.0-bin-hadoop2. ...

  8. oracle调优 浅析有效的游标管理

    浅析有效的游标管理 [思路分析] 能够把游标理解成共享的运行计划,当sql不被共享时.常规的解决思路有两个方向: 1.调整共享池的尺寸(共享池的库缓存区中共享运行计划): 2.sql书写时尽量重用绑定 ...

  9. try....exception....finally

    class MyException(Exception): def __init__(self,msg): self.msg=msg def __str__(self): return self.ms ...

  10. taro + iview 实现跨平台开发(App,Wap,微信小程序)

    1.安装 (1)安装脚手架 npm install -g @tarojs/cli taro init myApp (2)H5端运行 npm run dev:h5 taro build --type h ...