我的程序有问题。在循环中,我使用多线程(这是我练习的前提)创建了一个新的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());
}
}
1条答案
按热度按时间i7uaboj41#
您应该在executorservice关闭后等待线程终止: