使用场景:

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

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

第一种:最简单的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. 使用.Net中的WeakDictionary — ConditionalWeakTable

    有的时候,我们需要给某些数据添加一些附加信息,一种常用的做法是使用一个Dictionary在填充这些附加信息如: var data = new Data();    var tag = new Tag ...

  2. easyui datagrid加载成功之后选定并获取首行数据

    //加载成功之后,选定并获取首行数据 onLoadSuccess:function(data){ alert("grid加载成功"); var rows=$('test').dat ...

  3. PostgreSQL配置文件--连接和认证

    1 连接和认证 CONNECTIONS AND AUTHENTICATION 1.1 连接 CONNECTIONS 1.1.1 listen_addresses 字符型 默认: listen_addr ...

  4. Drupal 7.31 SQL Injection Exp

    #-*- coding:utf-8 -*- import urllib2,sys import hashlib   # Calculate a non-truncated Drupal 7 compa ...

  5. kvm : Permission denied

    创建虚拟机类型为:“virt type :kvm” 时,会报如下错误: Could not access KVM kernel module: Permission denied failed to ...

  6. UI 层级问题

    UI 用overlay的话 不会有自己的camre 直接画到backbuffer上 比较推荐 分层的事情就用sorting order解决就可以了 下一步就是能不能拿到 ugui的shader了 UI ...

  7. angular 学习理解笔记

    原文:https://github.com/eoinkelly/notes/blob/master/angular/book-building-web-apps-w-angular/angular.m ...

  8. iOS学习笔记之蓝牙(有关蓝牙设备mac地址处理) 2

    1.创建中心设备,并设置代理 一般情况下,手机是中心设备,蓝牙设备是外围设备. self.centralManager = [[CBCentralManager alloc] initWithDele ...

  9. Session机制详细介绍

    Session机制详细介绍  

  10. Ubuntu系统进程绑定CPU核

    Ubuntu系统进程绑定CPU核 作者:chszs.版权全部,未经允许,不得转载. 博主主页:http://blog.csdn.net/chszs 本文讲述如何在Ubuntu系统中,把指定的进程绑定到 ...