java异步转同步

1.异步转同步,线程池提交任务,阻塞获取结果

ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) ThreadUtils.newDaemonFixedThreadExecutor("PodActionService"
            , Runtime.getRuntime().availableProcessors() + 1);

 public void delete(String instanceId) throws ExecutionException, InterruptedException {
        Future<ResourceStatus> future = threadPoolExecutor.submit(new DeletePodThread(instanceId));
        ResourceStatus resourceStatus = future.get();
        LOG.info("instanceId : {} destroy status : {}",instanceId,resourceStatus);
}

2.线程任务,返回值类型ResourceStatus枚举

public class DeletePodThread implements Callable<ResourceStatus> {

        public DeletePodThread(String instanceId) {
            this.instanceId = instanceId;
        }

        private String instanceId;

        @Override
        public ResourceStatus call() throws Exception {
            QueryWrapper<FamaVm> vmQueryWrapper = Wrappers.query();
            vmQueryWrapper.eq(FamaVm.INSTANCE_ID_COLUMN,instanceId);
            FamaVm famaVm = famaVmMapper.selectOne(vmQueryWrapper);
            if (null == famaVm){
                return null;
            }
            QueryWrapper<FamaPin> pinQueryWrapper = Wrappers.query();
            pinQueryWrapper.eq(FamaPin.PIN_COLUMN,famaVm.getPin());
            pinQueryWrapper.eq(FamaPin.PIN_ALIAS_COLUMN,famaVm.getPinAlias());
            FamaPin famaPin = famaPinMapper.selectOne(pinQueryWrapper);
            if (null == famaPin){
                return null;
            }
            PodService podService = new PodService(famaPin);
            DeletePodResponse deletePodResponse = podService.delete(famaVm);
            if (null != deletePodResponse.getError() && deletePodResponse.getError().getStatus().equalsIgnoreCase("NOT_FOUND" )){
                return ResourceStatus.DELETED;
            }
            InstanceStatus resourceStatus = describeResStatus(podService,famaVm);
            while (!resourceStatus.typeIsFinished()){
                ThreadUtils.sleep(Constants.SLEEP_TIME_MILLIS);
                resourceStatus = describeResStatus(podService,famaVm);
            }
            famaVmMapper.updateById(famaVm);
            ResourceInstance resourceInstance = processInstanceMapper.selectById(famaVm.getResourceInstanceId());
            resourceInstance.setState(resourceStatus);
            processInstanceMapper.updateById(resourceInstance);
            return famaVm.getState();
        }
    }
原文地址:https://www.cnblogs.com/PythonOrg/p/14603496.html