jdk中提供的
HashMap
,ArrayList
,HashSet
等都是不安全的 。如果在方法内部使用,是没有关系的 。如果需要跨线程使用,就需要注意线程安全的问题。
如下一个例子,插入4w次数据,得到的数据少于目标数据。
public static void main(String[] args) throws InterruptedException {
//
ExecutorService executorService = Executors.newCachedThreadPool();
CountDownLatch latch = new CountDownLatch(40000);
Map<Integer, Integer> maps = new HashMap<>();
for (int i = 0; i < 40000; i++) {
int finalI = i;
executorService.submit(new Runnable() {
@Override
public void run() {
maps.put(finalI, finalI);
latch.countDown();
}
});
}
latch.await();
System.out.println(maps.size());//少于4w个元素
executorService.shutdownNow();
}
···
网友评论