美文网首页
<>不安全的集合类

<>不安全的集合类

作者: monk87 | 来源:发表于2019-05-25 18:26 被阅读0次

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

    相关文章

      网友评论

          本文标题:<>不安全的集合类

          本文链接:https://www.haomeiwen.com/subject/udjzzqtx.html