Java 自增线程安全性测试及解决方案

i++线程不安全原因

  • 多个线程同时访问共享变量i,而JVM允许每个线程存储变量的副本,i++的操作可以分为三步: 取值、自增、写回。存在一个线程在 自增 时,刚好有线程在 取值,因此最后会出现i增加的结果总比预计的结果线程小。
  • 测试例:
class TestIPlus {
    private int val = 0;
    public void run() {
        for(int i=0; i<10; i++) {
            this.val = 0;
            final CountDownLatch count = new CountDownLatch(10000);
            for(int j=0; j<100; j++) {
                new Thread(){
                    @Override
                    public void run() {
                        for(int i=0; i<100; i++) {
                            TestIPlus.this.val++;
                            count.countDown();
                        }
                    }
                }.start();
            }
            try {
                count.await();
            } catch(InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(this.val);
        }
    }
}

使i++变得线程安全有3种方式:

  • 使用synchronized关键字,将i++写成一个方法,并使用synchronized修饰
public synchronized void incI() {
    this.i++;
}
  • 使用Lock,在修改i的位置加锁
private Lock lock = new ReentrantLock();
public void incI() {
    lock.lock();
    try {
        i++;
    } finally {
        lock.unlock();
    }
}
  • 使用原子类AtomicInteger
class TestIPlus {
    private AtomicInteger val;
    public void run() {
        for(int i=0; i<10; i++) {
            this.val = new AtomicInteger(0);
            final CountDownLatch count = new CountDownLatch(10000);
            for(int j=0; j<100; j++) {
                new Thread() {
                    @Override
                    public void run() {
                        for(int i=0; i<100; i++) {
                            // 原子类自增
                            TestIPlus.this.val.getAndIncrement();
                            count.countDown();
                        }
                    }
                }.start();
            }
            try {
                count.await();
            } catch(InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(this.val);
        }
    }
}
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值