java多线程方法向synchronized arraylist添加对象

mi7gmzs6  于 2021-06-27  发布在  Java
关注(0)|答案(1)|浏览(437)

我的程序有问题。在循环中,我使用多线程(这是我练习的前提)创建了一个新的employes(通过从假名字生成器网站下载数据来自动创建),如果线程完成了employee对象的创建,我应该将其添加到synchronized list中,但是出现了问题,列表为空。我卡住了。有人知道怎么了吗?

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Stream;

public class Main {
    public static void main(String[] args) throws Exception {
        final String[][] e = new String[1][1];
        EmployeesGenerator a=new EmployeesGenerator();
        List<Employees> list= Collections.synchronizedList(new ArrayList<>());
        ExecutorService executorService= Executors.newFixedThreadPool(10);

       for(int x=0; x<10;x++){
           executorService.submit(()->{
                       try {
                           e[0] =a.getEmployees();
                       } catch (Exception ex) {
                           ex.printStackTrace();
                       }
                       list.add(new Employees(e[0][0], e[0][1], e[0][2], e[0][3], e[0][4]));
                        }
                   );
       }
       executorService.shutdown();

        System.out.println(list.size());
    }
}
i7uaboj4

i7uaboj41#

您应该在executorservice关闭后等待线程终止:

try {
        executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
    } catch (InterruptedException e) {
    }
    System.out.println(list.size());

相关问题