ExecutorService executorService = Executors.newFixedThreadPool(10); //使用1000个线程模拟 for (int i = 0; i < 1000; i++) { executorService.execute(runnable); } try { TimeUnit.SECONDS.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } }
报错信息
1 2 3 4 5 6 7
Exception in thread "pool-1-thread-2" java.util.ConcurrentModificationException at java.base/java.util.ArrayList.sort(ArrayList.java:1752) at java.base/java.util.Collections.sort(Collections.java:145) at com.example.surf.content.Demo2$1.run(Demo2.java:34) at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) at java.base/java.lang.Thread.run(Thread.java:834)
int index = 0; for (Config config : configs) { index += config.getRatio(); if (index >= randomId) { return config; } } return configs.get(0); }
1 2 3 4 5 6 7
2021-07-07 04:38:13.975 ERROR 1 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.util.ConcurrentModificationException] with root cause java.util.ConcurrentModificationException: null at java.base/java.util.ArrayList.sort(ArrayList.java:1751) ~[na:na] at java.base/java.util.Collections.sort(Collections.java:177) ~[na:na] at com.example.surf.content.controller.ContentController.getConfigByRandomId(ContentController.java:163) ~[classes!/:0.0.1-SNAPSHOT] at com.example.surf.content.controller.ContentController.layer(ContentController.java:77) ~[classes!/:0.0.1-SNAPSHOT] at jdk.internal.reflect.GeneratedMethodAccessor132.invoke(Unknown Source) ~[na:na]