how to use Multithreading With ArrayList in Java

空扰寡人 提交于 2020-01-11 08:03:11

问题


Hello ,

I have a program that works perfectly , unfortunantly i have some calculs that takes a lot of time , some minutes ..

My objectif is to use multithreading to accelerate the parts that take so much time ,.

In this Example I give the prototype of the part that i should parallelize

public static ArrayList<Object2> createListOfObject2(ArrayList<Object1> mylist) {
    ArrayList<Object2> listToReturn = new ArrayList<>();
    Object2 object2;
    for (int i = 0; i < mylist.size(); i++) {
        for (int j = 0; j < mylist.size(); j++) {
            object2 = heavyCalcul(mylist, i, j);
            listToReturn.add(object2);
        }
    }
    return listToReturn;
}
private static Object2 heavyCalcul(ArrayList<Object1> mylist, int i, int j) {
    int weight = MyCalculator.getInstance().calcul(mylist.get(i),mylist.get(j));
    Object2 Object2 = new Object2(weight);
    return Object2;
}

As you ca see , the method

public static ArrayList<Object2> createListOfObject2(ArrayList<Object1> mylist)

get a list of Object1 , and should create another list of object2 .

I made a twoo foor Loop , and each time i create an object2 forming by two object , it should take O(n²) times.

for bigger list it takes a long time.

So where should I put the multithreding and wich type of list i should use.

The second Problem is that the class MyCalculator is a singleton Class , and i create only one object of it , and in my opinion even using multhitreading the real program will not benefit of multhitreading .

What are the rules i should follow to use multhitreading ?

Many Thanks.


回答1:


The fact that your object is a singleton is irrelevant. What matters is shared mutable state. So, if your computation don't mutate shared state, and every computation is thus independant from the others, you can just use a parallel stream:

myList.parallelStream()
      .flatMap(first -> myList.stream().map(second -> MyCalculator.getInstance().calcul(first, second)))
      .collect(Collectors.toList());


来源:https://stackoverflow.com/questions/47618044/how-to-use-multithreading-with-arraylist-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!