java中原子变量AtomicInteger等用法

       在java中的变量在++等操作是不是原子操作,分为先加一,然后赋值,从而在多线程编码时需要加上synchronizeed,为了增加易用性,java当前提供了原子变量,当前的原子变量有AtomicBoolean、AtomicInteger、AtomicLong、AtomicReference等,其特点就是操作的原子性,以下代码演示了他们的用法。

 

package AtomicTest;

import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

import org.junit.Assert;
import org.junit.Test;

public class AtomicTest {
    AtomicInteger atomicInteger = new AtomicInteger(0);
    AtomicBoolean atomicBoolean = new AtomicBoolean(true);
    
    private enum State {     
        NEW, INITIALIZING, INITIALIZED     
    };   
    AtomicReference<State> atomicReference = new AtomicReference<State>(State.NEW);
    
    @Test
    public void testAtomicInteger() {
        
        atomicInteger.addAndGet(2);
        Assert.assertEquals(atomicInteger.get(), 2);
        
        atomicInteger.decrementAndGet();
        Assert.assertEquals(atomicInteger.get(), 1);
    }
    
    @Test
    public void testAtomicBoolean() {
        
        atomicBoolean.set(false);
        Assert.assertEquals(atomicBoolean.get(), false);
        
        atomicBoolean.getAndSet(true);
        Assert.assertEquals(atomicBoolean.get(), true);
    }
    
    @Test
    public void testAtomicReference() {
        
        Assert.assertEquals(atomicReference.get(), State.NEW);
        
        atomicReference.getAndSet(State.INITIALIZED);
        Assert.assertEquals(atomicReference.get(), State.INITIALIZED);
    }
}

 

 

 

 

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值