如何在 Java 中使用多线程和 ArrayList [英] how to use Multithreading With ArrayList in Java
问题描述
你好,
我有一个完美运行的程序,不幸的是我有一些计算需要很多时间,几分钟..
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;
}
如你所见,方法
public static ArrayList<Object2> createListOfObject2(ArrayList<Object1> mylist)
获取 Object1 的列表,并且应该创建另一个 object2 的列表.
get a list of Object1 , and should create another list of object2 .
我做了一个 twoo foo 循环,每次我创建一个由两个 object 形成的 object2 时,它应该花费 O(n²) 次.
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.
第二个问题是 MyCalculator 类是一个单例类,我只创建了它的一个对象,在我看来,即使使用多读,真正的程序也不会从多读中受益.
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 ?
非常感谢.
推荐答案
您的对象是单例这一事实无关紧要.重要的是共享可变状态.因此,如果您的计算不改变共享状态,并且每个计算都因此独立于其他计算,您可以只使用并行流:
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());
这篇关于如何在 Java 中使用多线程和 ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!