《转载》多线程并行编程解决同时访问多个接口过慢的问题

原文地址:多线程并行编程解决同时访问多个接口过慢的问题_金刚程序娃_新浪博客
http://blog.sina.com.cn/s/blog_152390b5e0102yv09.html

 



import java.util.concurrent.Callable;

//注:本人用service层模拟访问的接口,返回值是JSON
//处理问题:从不同的接口地址或数据库表同时获取信息,可以使用多线程并行编程的设计
//执行的总时间取决于最慢线程的时间
@RequestMapping("/userinfo")
@Controller
public class UserControllerThread {

	@Autowired
	private UserService userService;

	@RequestMapping(value = "/getUserinfo-api", method = RequestMethod.GET)
	@ResponseBody
	public JSONObject userInfoList(@RequestParam String userId) throws InterruptedException, ExecutionException {

		long currentTimeMillis = System.currentTimeMillis();

		Callable userInfoCallable = new Callable() {

			@Override
			public JSONObject call() throws Exception {
				long currentTimeMillis = System.currentTimeMillis();
				String user = userService.getInfo(userId);
				JSONObject userInfo = JSONObject.parseObject(user);
				String threadName = Thread.currentThread().getName();
				System.out.println(threadName + " > userInfo 耗时" + (System.currentTimeMillis() - currentTimeMillis));
				return userInfo;
			}
		};

		Callable intergralCallable = new Callable() {

			@Override
			public JSONObject call() throws Exception {
				long currentTimeMillis = System.currentTimeMillis();
				String intergral = userService.getIntegral(userId);
				JSONObject intergralInfo = JSONObject.parseObject(intergral);
				String threadName = Thread.currentThread().getName();
				System.out.println(threadName + " > intergralInfo 耗时" + (System.currentTimeMillis() - currentTimeMillis));
				return intergralInfo;
			}
		};

		FutureTask userInfoTask = new FutureTask(userInfoCallable);
		FutureTask intergralInfoTask = new FutureTask(intergralCallable);

		new Thread(userInfoTask).start();
		new Thread(intergralInfoTask).start();

		JSONObject result = new JSONObject();
		result.putAll(userInfoTask.get());
		result.putAll(intergralInfoTask.get());
		String threadName = Thread.currentThread().getName();
		System.out.println(threadName + " > 总 耗时:" + (System.currentTimeMillis() - currentTimeMillis));
		System.out.println(result);
		return result;
	}
}

 

你可能感兴趣的:(java基础,java线程)