package com.pingan.fic.trade.thread;
import com.alibaba.fastjson.JSONObject;
import org.junit.Test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;
/**
* ExecutorServiceTest
* Created by MAKUN649 on 2017/2/15.
*/
public class ExecutorServiceTest {
ExecutorService executorService = Executors.newFixedThreadPool(3);
final String request1 = "request1";
final String request2 = "request2";
final String request3 = "request3";
@Test
public void testFutureTask() throws InterruptedException, ExecutionException {
FutureTask<Map> futureTask1 = new FutureTask<>(new Callable<Map>() {
@Override
public Map call() throws Exception {
return getResult(request1);
}
});
FutureTask<Map> futureTask2 = new FutureTask<>(new Callable<Map>() {
@Override
public Map call() throws Exception {
return getResult(request2);
}
});
FutureTask<Map> futureTask3 = new FutureTask<>(new Callable<Map>() {
@Override
public Map call() throws Exception {
return getResult(request3);
}
});
executorService.submit(futureTask1);
executorService.submit(futureTask2);
executorService.submit(futureTask3);
Map<String,Object> result1 = futureTask1.get();
Map<String,Object> result2 = futureTask2.get();
Map<String,Object> result3 = futureTask3.get();
List<String> list1 = (List<String>) result1.get("data");
List<String> list2 = (List<String>) result2.get("data");
List<String> list3 = (List<String>) result3.get("data");
list1.addAll(list2);
list1.addAll(list3);
System.out.println("result list : " + JSONObject.toJSONString(list1));
}
@Test
public void testFuture() throws ExecutionException, InterruptedException {
Future<Map> future1 = executorService.submit(new Callable<Map>() {
@Override
public Map call() throws Exception {
return getResult(request1);
}
});
Future<Map> future2 = executorService.submit(new Callable<Map>() {
@Override
public Map call() throws Exception {
return getResult(request2);
}
});
Future<Map> future3 = executorService.submit(new Callable<Map>() {
@Override
public Map call() throws Exception {
return getResult(request3);
}
});
Map<String,Object> result1 = future1.get();
Map<String,Object> result2 = future2.get();
Map<String,Object> result3 = future3.get();
List<String> list1 = (List<String>) result1.get("data");
List<String> list2 = (List<String>) result2.get("data");
List<String> list3 = (List<String>) result3.get("data");
list1.addAll(list2);
list1.addAll(list3);
System.out.println("result list : " + JSONObject.toJSONString(list1));
}
private Map<String,Object> getResult(String request) throws InterruptedException {
Map<String,Object> result = new HashMap<>();
List<String> list = new ArrayList<>();
for (int i = 0 ; i < 10 ; i ++){
list.add(request+":"+i);
}
result.put("rtnCode","0000");
result.put("rtnMsg","查询成功");
result.put("data",list);
Thread.sleep(5000);
System.out.println(request+"查询成功");
return result;
}
}
网友评论