“线程中的异常”;“主要”;多线程时的java.util.ConcurrentModificationException

“线程中的异常”;“主要”;多线程时的java.util.ConcurrentModificationException,java,multithreading,parallel-processing,synchronization,java-threads,Java,Multithreading,Parallel Processing,Synchronization,Java Threads,我正在开发一个多线程程序,目的是通过三个线程同时在一个列表中添加150000名学生,这意味着每个学生将添加50000名。以下是节目: public class ThreadsStudents implements Runnable { public static List<Student> students = new ArrayList<>(); @Override public void run() { fo

我正在开发一个多线程程序,目的是通过三个线程同时在一个列表中添加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.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);
}
你能帮我吗


提前感谢您的帮助

您的程序几乎没有问题

  • 在ThreadStudents的所有线程完成之前,您的程序将返回到主线程。因此,您试图在所有线程都写入之前读取,这就是为什么会出现concurrentModification异常

  • students是ArrayList对象,这意味着它不是线程安全的

    公共类主{
    公共静态void main(字符串[]argv){
    对于(int i=0;i<1;i++){
    ThreadStudents.threadsL(3);
    System.out.println(ThreadStudents.students.size());
    }
    }
    }
    公共类ThreadStudents实现Runnable{
    public static List students=new CopyOnWriteArrayList();
    //数组列表的线程安全版本
    @凌驾
    公开募捐{
    System.out.println(“开始:+Thread.currentThread().getName());
    对于(int i=0;i<50000;i++){
    增加(1);
    }
    System.out.println(“结束”+Thread.currentThread().getName());
    }
    公共静态void threadsL(int-nbThreads){
    ExecutorService executor=Executors.newFixedThreadPool(nbThreads);
    //创建固定数量的线程
    对于(int i=0;i
  • 我的产量和预期完全一样,是150000

    Starting: pool-1-thread-3
    Starting: pool-1-thread-1
    Starting: pool-1-thread-2
    Ending pool-1-thread-3
    Ending pool-1-thread-1
    Ending pool-1-thread-2
    150000
    

    这回答了你的问题吗@不,如果我使用ListIterator也不起作用
    Starting: pool-1-thread-3
    Starting: pool-1-thread-1
    Starting: pool-1-thread-2
    Ending pool-1-thread-3
    Ending pool-1-thread-1
    Ending pool-1-thread-2
    150000