我有两节课

public class Account {

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getCompany() {
        return company;
    }
    public void setCompany(String company) {
        this.company = company;
    }
    public String name;
    public String company;
}



public class Estimates {

    public String market;
    public String getMarket() {
        return market;
    }
    public void setMarket(String market) {
        this.market = market;
    }
    public Account getAccount() {
        return account;
    }
    public void setAccount(Account account) {
        this.account = account;
    }
    public Account account;
}

Estiments对象被创建1000次,我必须迭代For Each循环中的Estiments对象,并执行一些计算谁的结果存储在Account对象中,并设置回Estimate对象.

for(Estimates estimate : estimateList)
{
// account is a result of some calculation
estimate.setAccount(account);
}

这是以顺序方式发生的,并造成了执行延迟,这可以转换为使用Java线程的并行执行吗? 每个Account对象都调用一个执行某些计算的方法.

推荐答案

这是以顺序方式发生的,并造成了执行延迟,这可以转换为使用Java线程的并行执行吗?

是的,可以通过这种方式提高性能.

可能的解决方案为Java Thread:

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class Main {

    public static void main(String[] args) {
        List<Estimates> estimateList = ... // Set the list of Estimates objects here

        int numThreads = 3; // set the number of threads you want to use
        ExecutorService executorService = Executors.newFixedThreadPool(numThreads);

        try {
            int chunkSize = estimateList.size() / numThreads;

            for (int i = 0; i < numThreads; i++) {
                int startIndex = i * chunkSize;
                int endIndex = (i == numThreads - 1) ? estimateList.size() : (startIndex + chunkSize);
                List<Estimates> chunk = estimateList.subList(startIndex, endIndex);

                executorService.execute(() -> {
                    for (Estimates estimate : chunk) {
                        Account account = performCalculations(estimate);
                        estimate.setAccount(account);
                    }
                });
            }
        } finally {
            executorService.shutdown();
            try {
                executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
            } catch (InterruptedException e) {
                // Put the handling of a thread interruption here
            }
        }
    }

    private static Account performCalculations(Estimates estimate) {
        // do your calculations and return the Account object here
        return new Account();
    }
}

此外,我还建议采取其他 Select .

你可以用java Stream API.

       List<Estimates> updatedEstimates = estimateList.parallelStream()
            .map(estimate -> {
                Account account = performCalculations(estimate);
                estimate.setAccount(account);
                return estimate;
            })
            .collect(Collectors.toList());

Java相关问答推荐

如何在Spring Boot中创建500错误的响应正文?

虚拟线程似乎在外部服务调用时阻止运营商线程

Java在模块化jar文件中找不到类,但是javap可以

了解Android Studio中的调试器输出

如果一个子类没有构造函数,超类也没有构造函数,那么为什么我可以构造子类的实例呢?

无法传递消费者<;>;实例

为什么BasicComboBoxRenderer在文本不存在或文本为空的情况下设置两次文本?

Java函数式编程中的双值单值映射

如何从错误通道回复网关,使其不会挂起

如何在Spring Java中从数据库列中获取JSON中的具体数据

如何在Java记录中设置BigDecimal类型属性的精度?

如何在EXCEL单元格中添加形状和文本

Sack()步骤中的合并运算符未按预期工作

迁移到Java 17后,日期显示不准确

如何使用路径过渡方法使 node 绕圆旋转?

垃圾收集时间长,会丢弃网络连接,但不会在Kubernetes中反弹Pod

如何从HttpResponse实例获取Entity对象的内容?

如何在IntelliJ IDEA的Build.sbt中添加外部JAR文件?

在WHILE()循环初始化部分中声明和初始化变量的Java语法?

JAVA 正则表达式识别字符串string或字符串内的字符char