spring boot 处理多线程的解决方案

spring boot 处理多线程的解决方案(不知道可不可行),如果有更好的方案请指教


思路:用户的请求采用callable 来处理用户的每个请求,每个请求都给予回应, 那么线程池的size 就要根据并发数量决定了, 暂定30个


加入msg 是为了校验请求的发出者和多线程返回的结果对应上(观察msg返回值是否是用户请求的原始值,如果不是就说明多线程出现了相互干扰)

http://localhost:8080/test?msg=google

http://localhost:8080/test?msg=搜狗


返回的结果必然要和“msg” 里面的值对应上,不然就是出错了


package com.example.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MultiController {
	
	
	@RequestMapping("/test")
	public List<String> test(@RequestParam("msg") String msg ,HttpServletRequest request){
		List<String> list = new ArrayList<>();
		
		int taskSize = 30;
		ExecutorService pool = Executors.newFixedThreadPool(taskSize);
		
		Callable<List<String>> call =createCallable(request , msg);

		try {
			Future<List<String>> future = pool.submit(call);
			if(!future.isDone()){
				Thread.sleep(2000);
			}
			if(future.isDone()){
				list.addAll(future.get());
			}
			pool.shutdown();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		return list;
	}

	private Callable<List<String>>  createCallable(final HttpServletRequest request, final String msg) {
		Callable<List<String>> call = new Callable<List<String>>() {

			@Override
			public List<String> call() throws Exception {
				List<String> list = new ArrayList<>();
				/*for(int i=0; i<100; i++){
					list.add(UUID.randomUUID().toString());
				}*/
				list.add("time :"+System.currentTimeMillis()+ " :request:"+ request.hashCode()+ " msg:"+ msg);
				System.out.println(list);
				return list;
			}
		};
		return call;
	}

}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值