如何使用Spring多线程
为什么使用Spring多线程
实际有两个原因,第一使用Spring比使用JDK原生的并发API更简单。第二我们的应用环境一般都会集成Spring,我们的Bean也都交给Spring来进行管理,那么使用Spring来实现多线程更加简单,更加优雅。(更多的可能是在环境中就要这么用!!)
定义配置类
package com.ysl.thread_demo.utils;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
@Configuration
@EnableAsync // 启用异步任务
public class ThreadConfig implements AsyncConfigurer {
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.setCorePoolSize(4);
taskExecutor.setMaxPoolSize(20);
taskExecutor.setQueueCapacity(30);
taskExecutor.initialize();
return taskExecutor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return null;
}
}
在业务层使用多线程
package com.ysl.thread_demo.service.serviceImpl;
import com.ysl.thread_demo.service.TestThreadService;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class TestThreadServiceImpl implements TestThreadService {
@Override
@Async //使用@Async开启一个线程
public void func01() throws Exception{
for (int i = 0; i < 5; i++) {
Thread.sleep(1000);
System.out.println("func01运行 = " + i);
}
}
@Override
@Async
public void func02() throws Exception {
for (int i = 0; i < 5; i++) {
Thread.sleep(1500);
System.out.println("func02运行 = " + i);
}
}
@Override
@Async
public void func03() throws Exception {
for (int i = 0; i < 5; i++) {
Thread.sleep(2000);
System.out.println("func03运行 = " + i);
}
}
}
使用controller层进行测试
package com.ysl.thread_demo.controller;
import com.ysl.thread_demo.service.TestThreadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestThreadController {
@Autowired
private TestThreadService testThreadService;
@RequestMapping(value = "/testThread")
public void testThread(){
try {
testThreadService.func01();
testThreadService.func02();
testThreadService.func03();
}catch (Exception e){
e.printStackTrace();
}
}
}