java ConcurrentHashMap多线程操作不安全

  1. 先看下面的代码
  public static void main(String[] args) {
        int threadNum;
        System.out.println("The Multi thread results:");
        threadNum = 5;
        for (int i = 0; i < 5; i++) {
            System.out.println("The " + (i + 1) + " Times Results:" + testAdd(threadNum));
        }
    }

    static class TestTask implements Runnable {
        private final ConcurrentHashMap<Integer, Integer> map;

        public TestTask(ConcurrentHashMap<Integer, Integer> map) {
            this.map = map;
        }

        @Override
        public void run() {
            for (int i = 0; i < 1000000; i++) {
//                synchronized (map) {
                    map.put(1, map.get(1) + 1);
//                }
            }
        }
    }

    private static int testAdd(int threadNum) {
        ConcurrentHashMap<Integer, Integer> map =
                new ConcurrentHashMap<Integer, Integer>() {{
                    put(1, 0);
                }};
        ThreadPoolExecutor pool = new ThreadPoolExecutor(threadNum, threadNum, 2000, TimeUnit.MILLISECONDS, new LinkedBlockingDeque<>());
//        ExecutorService pool= Executors.newCachedThreadPool();
        for (int i = 0; i < threadNum; i++) {
            pool.execute(new TestTask(map));
        }
        pool.shutdown();
        try {
            pool.awaitTermination(20, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return map.get(1);
    }

执行效果:

The Multi thread results:
The 1 Times Results:1436098
The 2 Times Results:1498073
The 3 Times Results:1568226
The 4 Times Results:1350195
The 5 Times Results:1442906

可以看到每次执行的效果都不一样,我们期望的是累加的结果500万,可结果都比它小很多.

主要是这个代码 map.put(1, map.get(1) + 1);

为什么呢,因为ConcurrentHashMap只保证了put()或者get()的原子性---原子性就是要么同时成功,要么同时失败,不会被别的操作影响.

所以map.put(1, map.get(1) + 1);这个代码不是原子性的操作,它先拿到值,然后加1在put更新

单线程不会有任何问题,但是多线程会有以下可能.

线程A执行了get方法,还没执行put方法,然后这个时候线程B也执行了get方法,他们拿到的结果都是一样的,然后都执行了put方法,把

多线程中.因此,我们需要在关键代码处加锁才能保证这个代码的原子性

 static class TestTask implements Runnable {
        private final ConcurrentHashMap<Integer, Integer> map;

        public TestTask(ConcurrentHashMap<Integer, Integer> map) {
            this.map = map;
        }

        @Override
        public void run() {
            for (int i = 0; i < 1000000; i++) {
                synchronized (map) {//加锁,逻辑上让其成为原子性操作
                    map.put(1, map.get(1) + 1);
                }
            }
        }
    }

这样执行的结果就是理想值了

The Multi thread results:
The 1 Times Results:5000000
The 2 Times Results:5000000
The 3 Times Results:5000000
The 4 Times Results:5000000
The 5 Times Results:5000000

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值