【发布时间】:2020-11-23 00:35:12
【问题描述】:
我正在开发一个多线程程序,目的是通过三个线程同时将 150000 个学生添加到一个列表中,这意味着每个人将添加 50000 个。这是以下程序:
public class ThreadsStudents implements Runnable {
public static List<Student> students = new ArrayList<>();
@Override
public void run() {
for(int i = 0; i < 50000; i++) {
students.add(Generator.generetorStudent());
}
}
public static void threadsL(int nbThreads) {
ArrayList<Thread> th = new ArrayList<>();
for(int i = 0; i < nbThreads; i++) {
th.add(new Thread(new ThreadsStudents()));
}
for(Thread threads: th) {
threads.start();
}
}
}
我要做的是从Main类调用方法threadsL,将学生列表添加到数据库中,然后计算15次执行的平均执行时间。
public class Main {
public static void main(String[] argv) {
long startDate,endDate;
double measure;
double average = 0;
ManipulationBDD basedd = new ManipulationBDD();
for (int i = 0; i < 15; i++) {
startDate = System.nanoTime();
ThreadsStudents.threadsL(3);
for(Student e : ThreadsStudents.students) {
basedd.insertTable(e);
}
endDate = System.nanoTime();
measure = (double) (endDate - startDate) / 1000000000;
average = average + measure;
basedd.empty();
}
average = average / 15;
System.out.println("The average is : " + average);
}
}
在Main.java 类中,我得到以下异常:
Exception in thread "main" java.util.ConcurrentModificationException
at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:1043)
at java.base/java.util.ArrayList$Itr.next(ArrayList.java:997)
at Main.main(Main.java:27)
第 27 行是:
for(Student e : ThreadsStudents.students) {
basedd.insertTable(e);
}
你能帮我解决这个问题吗?
提前感谢您的帮助!
【问题讨论】:
-
这能回答你的问题吗? Concurrent Modification exception
-
@null_awe 不,如果我使用 ListIterator 也不起作用
标签: java multithreading parallel-processing synchronization java-threads