gpt4 book ai didi

java7 - 是否可以多线程for循环?

转载 作者:行者123 更新时间:2023-12-02 10:27:23 24 4
gpt4 key购买 nike

我有一个循环大约 10 亿次的 for 循环。每次迭代中有许多数据库查询和计算。简化的伪代码如下所示:

for(int i=0, i<1000000000, i++){
query();
if(...){
compute();
}
}

如果我可以并行设置并运行多个线程,每个线程都会迭代数百万次,这将显着减少时间。

如果没有某种并行处理,则需要数月才能完成。在这种情况下是否可以通过实现线程来减少时间?我知道 Java8 中的新流功能,但升级到 java8 对我来说不是一个选择。

如果有一个易于理解的指南,那就太好了!提前致谢。

编辑:这里有更详细的代码。我可能会为每次插入多次检查数据库,并且在执行此操作之前必须处理数据。理想情况下,我希望多个线程分担工作负载。

for(int i = 1; i<=100000000; i++){
String pid = ns.findPId(i); //query
object g = findObject(pid) //query
if(g!=null){
if(g.getSomeProperty()!=null && g.getSomeProperty().matches(EL)){
int isMatch = checkMatch(pid); //query
if(isMatch == 0){
String sampleId = findSampleId(pid); //query
if(sampleId!=null){
Object temp = ns.findMoreProperties(sampleId); //query
if(temp!=null){
g.setSomeAttribute(temp.getSomeAttribute());
g.setSomeOtherProperty(temp.getSomeOtherProperty());
insertObject(g); //compute, encapsulate and insert into database table
}
}
}else{
//log
}
}
}

最佳答案

1) 评估并查看您是否需要 ThreadPoolExecutor:

ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(10);

2)为第一部分编写一个可调用

public class FindObjectCallable implements Callable<Object> {
...

@Override
public Object call() throws Exception {
String pid = ns.findPId(i); //query
return findObject(pid) //query
}
}

3)主要代码执行以下操作:

    ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(10);

List<Future<Object>> futures = new ArrayList<Future<Object>>(0);

for(int i = 1; i<=100000000; i++) {
FindObjectCallable callable = new FindObjectCallable( ns, i );
Future<Object> result = executor.submit(callable);
futures.add(result);
}

for( Future<Object> future: futures )
{
// do a java 7 lambda equivalent for the g processing part
}

关于java7 - 是否可以多线程for循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53848392/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com