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

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

  1. import java.util.*;
  2. import java.util.concurrent.*;
  3. import java.util.concurrent.atomic.*;
  4. /*
  5. * ava.util.concurrent中实现的原子操作类包括:
  6. AtomicBoolean、AtomicInteger、AtomicIntegerArray、AtomicLong、AtomicReference、
  7. AtomicReferenceArray。
  8. *
  9. */
  10. public class AtomicOperationDemo {
  11. static AtomicInteger count=new AtomicInteger(0);
  12. public static class AddThread implements Runnable{
  13. @Override
  14. public void run() {
  15. for(int k=0;k<1000;k++){
  16. count.incrementAndGet();
  17. }
  18. }
  19. }
  20. public static void AtomicIntShow(){
  21. System.out.println("AtomicIntShow() enter");
  22. ExecutorService threadpool =   Executors.newFixedThreadPool(10);
  23. for(int k=0;k<100;k++){
  24. threadpool.submit(new AddThread());
  25. }
  26. try {
  27. Thread.sleep(2000);
  28. } catch (InterruptedException e) {
  29. // TODO Auto-generated catch block
  30. e.printStackTrace();
  31. }
  32. /* output
  33. * AtomicIntShow() enter
  34. * result of acumulated sum=100000
  35. * AtomicIntShow() exit
  36. */
  37. System.out.println("result of acumulated sum="+count);
  38. threadpool.shutdown();
  39. System.out.println("AtomicIntShow() exit");
  40. return ;
  41. }
  42. }

Maintest.java

  1. public class Maintest {
  2. public static void main(String[] args) {
  3. AtomicOperationDemo.AtomicIntShow();
  4. }
  5. }
    1. /* output
    2. * result of acumulated sum=100000
    3. */
上一篇:JFinalo操作框架racle数据库


下一篇:Java中常见的锁分类以及对应特点