java atomiclong 使用_java并发:原子类之AtomicLong

原子类之AtomicLong

java线程中的操作,需要满足原子性、可见性等原则,比如i++这样的操作不具备原子性,

A线程读取了i,另一个线程执行i++,A线程再执行i++就会引发线程安全问题

推荐学习的AtomicInteger和AtomicLong博客

一个非原子性的自加引发的安全例子

下面的例子执行1000个线程,有意思的还Long自加比Interger更容易发现结果是比1000小。

package com.java.javabase.thread.base.concurrent.atomic;

import lombok.Data;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

import java.util.concurrent.TimeUnit;

@Slf4j

public class AtomicLongtest {

public static void main(String[] args) {

AtomicLongtest test =new AtomicLongtest();

Count count =test.new Count();

ExecutorService service = Executors.newCachedThreadPool();

for(int i=0;i<1000;i++){

service.execute(()->count.increace());

}

service.shutdown();

try {

service.awaitTermination(1, TimeUnit.DAYS);

} catch (InterruptedException e) {

e.printStackTrace();

}

log.info("End count :{}",count.getCount());

}

@Data

class Count{

private Long count=0L;

public void increace(){

log.info("count {}",count++);

}

}

}

通过syncronized方法

通过syncronized方法使得自加操作安全

使用AtomicLong满足原子性

使用AtomicLong满足原子性主要是实现了CAS

比较并交换(compare and swap, CAS),是原子操作的一种,可用于在多线程编程中实现不被打断的数据交换操作,从而避免多线程同时改写某一数据时由于执行顺序不确定性以及中断的不可预知性产生的数据不一致问题。 该操作通过将内存中的值与指定数据进行比较,当数值一样时将内存中的数据替换为新的值。

使用使用AtomicLong,1000个线程执行之后返回的结果是1000,保证了结果的正确

package com.java.javabase.thread.base.concurrent.atomic;

import lombok.Data;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

import java.util.concurrent.TimeUnit;

import java.util.concurrent.atomic.AtomicLong;

@Slf4j

public class AtomicLongTest2 {

public static void main(String[] args) {

AtomicLongTest2 test =new AtomicLongTest2();

Count count =test.new Count();

ExecutorService service = Executors.newCachedThreadPool();

for(int i=0;i<1000;i++){

service.execute(()->count.increace());

}

service.shutdown();

try {

service.awaitTermination(1, TimeUnit.DAYS);

} catch (InterruptedException e) {

e.printStackTrace();

}

log.info("End count :{}",count.getCount());

}

@Data

class Count{

private AtomicLong count=new AtomicLong(0);

public void increace(){

log.info("count {}",count.incrementAndGet());

}

}

}

AtomicLong的ABA问题

CAS有一个问题是ABA问题:

1.ABC三个线程

2.count=10,这时AB线程的内存值和预期值都是10

3.B线程把count修改100成功后,内存值是100

4.A线程又把count设置为10

5.这个时候内存值和预期值都是10

6.c线程是不知道A和B对count做了什么操作的

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值