【问题标题】:java using ExecutorService is not accelerating the programjava使用ExecutorService没有加速程序
【发布时间】:2016-09-23 14:42:06
【问题描述】:

我使用 Executor Service 调用了一个 REST 客户端服务。我以串行或并行方式检查时间,它需要相同的时间。

List<String> exeParallel(int start, int end){
List<String> people =  new ArrayList<String>();
byte maxthreads;
    int cores = Runtime.getRuntime().availableProcessors();
    maxthreads =  (byte) ((cores > 2)?cores-1:1); 
    ExecutorService executor = Executors.newFixedThreadPool(maxthreads);

for(Long i= start; i <= end; i++ ){
        Callable<ServiceResponse> callTask = getTask(i);
        Future<ServiceResponse> future = executor.submit(callTask);
   if(future != null){
       String result = .....;
       people.add(result);
    }
}

private Callable<ServiceResponse> getTask(int num){
return new Callable<ServiceResponse>(){
    @Override
    public ServiceResponsecall() throws Exception {
    ServiceRestClient serviceRestClient =ServiceRestClient.getInstance();
            return serviceRestClient.callservice(num);
        }

    };
}

【问题讨论】:

  • 好吧,如果你在未来用get() 阻止(这是你用.... 替换的相关代码),肯定会花费相同的时间。你想做什么?
  • @Tunaki 我想获取响应并将我需要的相关数据复制到一个字符串中

标签: java multithreading executorservice


【解决方案1】:

先提交所有任务,然后一次从他们那里获取结果。这意味着在您等待第一个结果的同时,其他结果也可能同时运行。

List<Future<ServiceResponse>> futures = new ArrayList<>();

for(Long i= start; i <= end; i++ )
    futures.add(executor.submit(getTask(i)));

for (Future<ServiceResponse> future : futures)
{
    if(future != null)
    {
        String result = .....;
        people.add(result);
    }
}

【讨论】:

    猜你喜欢
    • 2012-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-17
    • 1970-01-01
    • 1970-01-01
    • 2018-09-17
    • 1970-01-01
    相关资源
    最近更新 更多