目录
- 前言
- 实例
前言
什么是进程:
“进程”是操作系统的概念,一个独立运行的程序,就是一个“进程”。
什么是线程:
“线程”是由“进程创建”的,一个进程可以创建任意多的线程,每个线程都包含一些代码。线程中的代码会同主进程或者其他线程“同时运行”。
什么是多进程:
同一时间段,同时运行多个程序。
什么是多线程:
一个程序同时启动多个线程,也就是多个代码块同时运行。从而提高程序的运行效率。
二、并发和并行
什么是并发
多个线程同时访问同一资源
例:你正在吃饭,有人来敲门,你放下饭碗去开门,回来接着吃饭。
什么是并行
多个线程同时开始运行
例:你正在吃饭,来电话啦,你边吃饭边打电话
Java使用多线程的条件
批处理(批量上传,批量导出,批量更新)
查询大量数据
本文以查询为例,展示一下线程池的使用。
本文使用的多线程框架是Executor
Executor 框架是 Java5 之后引进的,在 Java5 之后,通过Executor来启动线程比使用 Thread 的start方法更好
实例
本实例只为展示多线程的方法,所以数据随便使用的一个user表,进行测试
controller
@RestController
public class MultiThreadController {
@Autowired
private ThredService thredService;
@GetMapping("/testThredData")
public List testThredData()
{
return thredService.getAllResult();
}
}
实体
@Data
@Accessors(chain=true)
public class User {
private String id;
private String name;
private String password;
}
dao
@Mapper
public interface BlogMapper {
List<User> getQueryData(@Param("start") Integer start,@Param("end") Integer end);
}
service
public interface ThredService {
public List getAllResult();
//每个线程分页查询
public List<User> getQueryData(Integer start, Integer end);
}
impl
@Service
public class ThredServiceImpl implements ThredService {
@Autowired
private MultiThreadQueryUtil multiThreadQueryUtil;
@Resource
private BlogMapper blogMapper;
@Override
public List getAllResult() {
return multiThreadQueryUtil.getMultiCombineResult();
}
@Override
public List<User> getQueryData(Integer start, Integer end) {
return blogMapper.getQueryData(start,end);
}
}
MultiThreadQueryUtil工具类
@Service
public class MultiThreadQueryUtil {
// @Autowired
// private WorkflowTask workflowTaskMapper;
/**
* 获取多线程结果并进行结果合并
* @return
*/
public List<List> getMultiCombineResult() {
//开始时间
long start = System.currentTimeMillis();
//返回结果
List<List> result = new ArrayList<>();
//查询数据库总数量
// int count = workflowTaskMapper.selectCountAll();
// Map<String,String> splitMap = ExcelLocalUtils.getSplitMap(count,5);
// int bindex = 1;
//Callable用于产生结果
List<Callable<List>> tasks = new ArrayList<>();
for (int i = 1; i <= 4; i++) {
//不同的线程用户处理不同分段的数据量,这样就达到了平均分摊查询数据的压力
// String[] nums = splitMap.get(String.valueOf(i)).split(":");
// int startNum = Integer.valueOf(nums[0]);
int startNum =0;
int endNum =1;
Callable<List> qfe = new ThredQuery(startNum, endNum);
tasks.add(qfe);
startNum++;
endNum++;
}
try{
//定义固定长度的线程池 防止线程过多,5就够用了
ExecutorService executorService = Executors.newFixedThreadPool(5);
//Future用于获取结果
List<Future<List>> futures=executorService.invokeAll(tasks);
//处理线程返回结果
if(futures!=null&&futures.size() > 0){
for (Future<List> future:futures){
result.addAll(future.get());
}
}
//关闭线程池,一定不能忘记
executorService.shutdown();
}catch (Exception e){
e.printStackTrace();
}
long end = System.currentTimeMillis();
System.out.println("线程查询数据用时:"+(end-start)+"ms");
return result;
}
}
ThredQuery线程执行方法类
package com.baizhi.utils;
import com.baizhi.service.ThredService;
import java.util.List;
import java.util.concurrent.Callable;
public class ThredQuery implements Callable<List> {
public static SpringContextUtil springContextUtil = new SpringContextUtil();
private int start;
private int end;
//每个线程查询出来的数据集合
private List datas;
public ThredQuery(int start,int end) {
this.start=start;
this.end=end;
//每个线程查询出来的数据集合
ThredService thredService = springContextUtil.getBean(ThredService.class);
List count = thredService.getQueryData(start,end);
datas = count;
}
//返回数据给Future
@Override
public List call() throws Exception {
return datas;
}
}
SpringContextUtil
@Component
public class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
// 下面的这个方法上加了@Override注解,原因是继承ApplicationContextAware接口是必须实现的方法
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
SpringContextUtil.applicationContext = applicationContext;
}
public static Object getBean(String name)
throws BeansException {
return applicationContext.getBean(name);
}
public static Object getBean(String name, Class<?> requiredType)
throws BeansException {
return applicationContext.getBean(name, requiredType);
}
public static <T> T getBean(Class<T> clazz)
throws BeansException {
return applicationContext.getBean(clazz);
}
public static boolean containsBean(String name) {
return applicationContext.containsBean(name);
}
public static boolean isSingleton(String name)
throws NoSuchBeanDefinitionException {
return applicationContext.isSingleton(name);
}
public static Class<?> getType(String name)
throws NoSuchBeanDefinitionException {
return applicationContext.getType(name);
}
public static String[] getAliases(String name)
throws NoSuchBeanDefinitionException {
return applicationContext.getAliases(name);
}
}
使用postman测试