当开启多个线程处理数据时,用于存储的ArrayList需要进行转化成线程安全的ArrayList,通过Collections.synchronizedList()
public static boolean getSize() throws InterruptedException {
final int threadSize = 1000;
ListResp example1 = new ListResp(0, Collections.synchronizedList(new ArrayList<>()));
List<String> example2 = Collections.synchronizedList(new ArrayList<>());
final CountDownLatch countDownLatch = new CountDownLatch(threadSize);
ExecutorService executorService = Executors.newFixedThreadPool(40);
for (int i = 0; i < threadSize; i++) {
executorService.submit(() -> {
String uuid = UUID.randomUUID().toString();
example1.getFailList().add(uuid);
example2.add(uuid);
countDownLatch.countDown();
});
}
countDownLatch.await();
executorService.shutdown();
if (example2.size() != threadSize) {
throw new RuntimeException();
}
return example1.getFailList().size() == threadSize;
}