Java多线程返回值

我有一个循环一个过程的代码,该代码是这样的:

for (int z = 0; z < m_ID.length; z++) {
    expretdata = expret.Get_Expected_Return(sStartDate,sEndDate,m_ID[z],sBookName,nHistReturn,nmarketReturn,nCustomReturn);
    m_Alpha[z] = expretdata;
}

Get_Expected_Return()是一种花费太长时间的昂贵方法。因此,如果M_ID.length超过200,将需要一个小时才能完成任务。

我想使用多线程对其进行优化。我试图将返回值保存到Map静态全局变量中,并使用键对其进行重新排序。因为我需要按M_ID.length的索引对数据进行排序。

但是,当我尝试运行多线程时,某些线程返回值= NULL,看来该线程未运行该方法。

多线程是正确的方法吗?或给我任何优化建议。

qwezxcsl 回答:Java多线程返回值

如果昂贵的方法是独立的并且不使用过多的共享单一资源(例如单个硬盘驱动器),则多线程非常有用。

您可以使用Callables and Futures解决有序结果的用例:

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;


class Test
{       
    static final int CALLS = 10;

    static int slowMethod(int n) throws InterruptedException
    {
        Thread.sleep(1000);
        return n+1;
    }

    public static void main(String[] args) throws InterruptedException,ExecutionException
    {
        ExecutorService executor = Executors.newCachedThreadPool();
        List<Future<Integer>> futures = new ArrayList<>();

        for (int i = 0; i < CALLS ; i++)
        {
            final int finali = i;
            futures.add(executor.submit(()->slowMethod(finali)));               
        }
        for(Future<Integer> f: futures) {System.out.print(f.get());}
        executor.shutdown();
    }
}
,

如果您使用的是Java 8或更高版本,则可以使用parallelStream。

    m_Alpha = m_ID.parallelStream()
                 .map( z => {
                        return expret.Get_Expected_Return(sStartDate,sEndDate,m_ID[z],sBookName,nHistReturn,nMarketReturn,nCustomReturn);
                  })
                 .toArray(Integer[]::new);

提供给Array方法的构造函数的类型应与m_Alpha的类型相同。

,

您可以使用CompletableFuture并行执行此任务。这是一个例子。

// lets define a wrapper class which is responsible to put calculated data into the array-> 

private void longExecution(int index,DataType m_Alpah,... sStartDate,m_ID_index_z,nCustomReturn){
        m_Alpha[index] =  expret.Get_Expected_Return(sStartDate,nCustomReturn);
}

// Now from your code:

...
CompletableFuture[] futures = new CompletableFuture[m_ID.length];
for (int z = 0; z < m_ID.length; z++) {
   CompletableFuture.supplyAsync(() ->
                    longExecution(z,m_Alpah,sStartDate,nCustomReturn));
);
}
// waiting for completing all of the futures.
CompletableFuture.allOf(futures).join();


// After this line:
//m_Alpha <- array will hold the result.

本文链接:https://www.f2er.com/3153110.html

大家都在问