JAVA 中无锁的线程安全整数 AtomicInteger介绍和使用

21 篇文章 1 订阅

JAVA 中无锁的线程安全整数 AtomicInteger,一个提供原子操作的Integer的类。在Java语言中,++i和i++操作并不是线程安全的,在使用的时候,

不可避免的会用到synchronized关键字。而AtomicInteger则通过一种线程安全的加减操作接口。AtomicInteger为什么能够达到多而不乱,处理高并发应付自如呢?

这是由硬件提供原子操作指令实现的,这里面用到了一种并发技术:CAS。在非激烈竞争的情况下,开销更小,速度更快。
Java.util.concurrent中实现的原子操作类包括:
AtomicBoolean、AtomicInteger、 AtomicIntegerArray、AtomicLong、AtomicReference、 AtomicReferenceArray

/**
 * 来看AtomicInteger提供的接口。

 //获取当前的值
 
 public final int get()
 
 //取当前的值,并设置新的值
 
  public final int getAndSet(int newValue)
 
 //获取当前的值,并自增
 
  public final int getAndIncrement()
 
 //获取当前的值,并自减
 
 public final int getAndDecrement()
 
 //获取当前的值,并加上预期的值
 
 public final int getAndAdd(int delta) 


例子代码为:

AtomicOperationDemo.java

import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
/*
 * ava.util.concurrent中实现的原子操作类包括:
AtomicBoolean、AtomicInteger、AtomicIntegerArray、AtomicLong、AtomicReference、
AtomicReferenceArray。
 * 
 */
public class AtomicOperationDemo {
	   static AtomicInteger count=new AtomicInteger(0);
	   public static class AddThread implements Runnable{
		@Override
		public void run() {
			for(int k=0;k<1000;k++){
				count.incrementAndGet();
			}
		 } 
	   }
	   public static void AtomicIntShow(){
		 System.out.println("AtomicIntShow() enter");
		 ExecutorService threadpool =   Executors.newFixedThreadPool(10);
		 
		 for(int k=0;k<100;k++){
			 threadpool.submit(new AddThread());
		 }
		 
		 try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 
		 /* output
		  * AtomicIntShow() enter
		  * result of acumulated sum=100000
		  * AtomicIntShow() exit
		  */
		 
		 System.out.println("result of acumulated sum="+count);
		 threadpool.shutdown();
		 System.out.println("AtomicIntShow() exit");
		 return ;
		
	}
}


Maintest.java

public class Maintest {
	public static void main(String[] args) {
		AtomicOperationDemo.AtomicIntShow();
	}
}

  1. /* output 
  2.           * AtomicIntShow() enter 
  3.           * result of acumulated sum=100000 
  4.           * AtomicIntShow() exit 
  5.           */  

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值