Java 多线程
前不久换了新的工作环境,刚入职一周,这周主要熟悉代码。里面用了很多jdk1.8的东西。项目很复杂,学习!
多线程学习:Java多线程之Executor、ExecutorService、Executors、Callable、Future与FutureTask
Java多线程中有两种不同类型的任务,Runnable类型任务(无返回值)与Callable类型任务(有返回值)。
主要记录一下ExecutorService、Executors、Callable、Future的使用…需要请求其它服务,拿到结果,所以使用Callable类型任务。
/**
* @author Jiangcheng Xiang
*/
@Component
public class TestExecutor {
private final ExecutorService executorService = Executors.newFixedThreadPool(4);
@Autowired
private RequestValidatorExecutor validator;
public List<PricingFlightResponse> whiteScreenPricing(PricingFlightRequest request) {
// 校验数据
/**
* Validate the pricing request.
*/
ValidationResult result = validator.validate(request);
/**
* Return if there is error.
*/
String sessionId = request.getSessionId();
if (result.hasErrors()) {
return Collections.singletonList(PricingFlightResponse.error(ErrorCodes.VALIDATION, result.errors(), sessionId));
}
// 封装request数据
List<PricingFlightRequest> requests = manipulateRequest(request);
List<PricingFuture> futures = new ArrayList<>();
for (PricingFlightRequest pricingFlightRequest : requests) {
Future<PricingFlightResponse> future = executorService.submit(new Callable<PricingFlightResponse>() {
@Override
public PricingFlightResponse call() {
return doPricing(pricingFlightRequest);
}
});
// 上面的代码可以改写为lambda
// Future<PricingFlightResponse> future = executorService.submit(() -> doPricing(pricingFlightRequest));
futures.add(new PricingFuture("test", future));
}
// 从future中拿到数据
List<PricingFlightResponse> responses = new ArrayList<>();
for (PricingFuture future : futures) {
// get方法会阻塞直到结果返回
PricingFlightResponse response = future.get();
responses.add(response);
}
return null;
}
// 封装一个类 将线程和gds绑定起来 方便打印日志
class PricingFuture {
private String gds;
private Future<PricingFlightResponse> future;
public PricingFuture(String gds, Future<PricingFlightResponse> future) {
this.gds = gds;
this.future = future;
}
public PricingFlightResponse get() {
try {
return future.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
return null;
}
public String getGds() {
return gds;
}
}
// 封装request
private List<PricingFlightRequest> manipulateRequest(PricingFlightRequest pricingFlightRequest) {
// 这里将需要封装的数据放到request中
return null;
}
// 真正核价 请求其它微服务
private PricingFlightResponse doPricing(PricingFlightRequest pricingFlightRequest) {
return null;
}
}