涉及场景:客户需求购票时为手牌写入闸机权限,但是闸机数量较多,授权缓慢,然后没办法,就想这多开几个线程一起跑
/**
* 授权闸机线程体
* @author xyl
* @date 2022/7/1 12:28
* @explain
*/
public class MachineCallable implements Callable<DaHuaResult> {
/**大华云工具类*/
private DaHuaYunUtil daHuaYunUtil;
/**大华云睿的授权人员ID*/
private String fileId;
/**闸机设备编号*/
private String deviceId;
public MachineCallable(String fileId, String deviceId,DaHuaYunUtil daHuaYunUtil) {
this.fileId = fileId;
this.deviceId = deviceId;
this.daHuaYunUtil = daHuaYunUtil;
}
@Override
public DaHuaResult call() throws Exception {
AuthGateMachineDto authGateMachineDto = new AuthGateMachineDto();
authGateMachineDto.setPersonFileId(fileId);
authGateMachineDto.setOperateType(2);
authGateMachineDto.setDeviceId(deviceId);
authGateMachineDto.setChannelId(0);
DaHuaResult authResult = daHuaYunUtil.addAuthGateMachine(authGateMachineDto);
return authResult;
}
实现方法
/**
* 授权闸机
*
* @param bracelet
* @param machine
* @return {@link }
* @author xyl
* @date 2022/7/1 14:26
* @explain
*/
private void authMachine(Bracelet bracelet, List<GateMachine> machine) {
long l = System.currentTimeMillis();
if (machine != null && machine.size() > 0) {
//给与线程数
ExecutorService executorService = Executors.newFixedThreadPool(machine.size());
//线程返回结果list
ArrayList<Future<DaHuaResult>> futures = new ArrayList<>();
//遍历闸机
for (GateMachine gateMachine : machine) {
//创建线程
MachineCallable machineCallable = new MachineCallable(bracelet.getPersonFileId(), gateMachine.getDeviceId(), daHuaYunUtil);
//开启线程
Future<DaHuaResult> submit = executorService.submit(machineCallable);
//加入结果集
futures.add(submit);
}
//遍历结果集结果
for (Future<DaHuaResult> future : futures) {
try {
DaHuaResult result = future.get();
if (!result.getSuccess()) {
throw new BackendException(result.getErrMsg());
}
} catch (Exception e) {
throw new BackendException(e.getMessage());
} finally {
System.out.println("共耗时:" + (System.currentTimeMillis() - l) / 1000.0 + "s");
//关闭线程
executorService.shutdownNow();
}
}
//关闭线程
executorService.shutdownNow();
}
System.out.println("总共耗时:" + (System.currentTimeMillis() - l) / 1000.0 + "s");
}
本人也是第一次玩,显然很多需要优化,但是对线程了解的也不是很多,不知道哪里可以优化的,如果有大神请给点建议