【问题标题】:MultiThread method adding Object to synchronized ArrayList多线程方法将对象添加到同步的 ArrayList
【发布时间】:2021-01-07 14:01:27
【问题描述】:

我的程序有问题。在循环中,我在 multiThread(这是我练习的前提)中创建了一个新的 Employes(通过从假名称生成器网站自动下载数据),如果线程完成创建 Employee 对象应该将其添加到同步列表但出现问题并列出是空的。我卡住了。有人知道怎么回事吗?

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());
    }
}

【问题讨论】:

    标签: java arrays multithreading synchronization


    【解决方案1】:

    你应该在executorService关闭后等待线程的终止:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-12
      • 1970-01-01
      • 2015-05-24
      相关资源
      最近更新 更多