Java AtomicInteger类的使用方法详解

作者:叶长风 时间:2023-03-09 00:57:57 

首先看两段代码,一段是Integer的,一段是AtomicInteger的,为以下:


public class Sample1 {
 private static Integer count = 0;
 synchronized public static void increment() {
   count++;
 }
}

以下是AtomicInteger的:


public class Sample2 {
 private static AtomicInteger count = new AtomicInteger(0);
 public static void increment() {
   count.getAndIncrement();
 }
}

以上两段代码,在使用Integer的时候,必须加上synchronized保证不会出现并发线程同时访问的情况,而在AtomicInteger中却不用加上synchronized,在这里AtomicInteger是提供原子操作的,下面就对这进行相应的介绍。

AtomicInteger介绍

AtomicInteger是一个提供原子操作的Integer类,通过线程安全的方式操作加减。

AtomicInteger使用场景

AtomicInteger提供原子操作来进行Integer的使用,因此十分适合高并 * 况下的使用。

AtomicInteger源码部分讲解


public class AtomicInteger extends Number implements java.io.Serializable {
 private static final long serialVersionUID = 6214790243416807050L;
 // setup to use Unsafe.compareAndSwapInt for updates
 private static final Unsafe unsafe = Unsafe.getUnsafe();
 private static final long valueOffset;
 static {
   try {
     valueOffset = unsafe.objectFieldOffset
       (AtomicInteger.class.getDeclaredField("value"));
   } catch (Exception ex) { throw new Error(ex); }
 }
 private volatile int value;

以上为AtomicInteger中的部分源码,在这里说下其中的value,这里value使用了volatile关键字,volatile在这里可以做到的作用是使得多个线程可以共享变量,但是问题在于使用volatile将使得VM优化失去作用,导致效率较低,所以要在必要的时候使用,因此AtomicInteger类不要随意使用,要在使用场景下使用。

AtomicInteger实例使用

以下就是在多线程情况下,使用AtomicInteger的一个实例,这段代码是借用IT宅中的一段代码。


public class AtomicTest {
 static long randomTime() {
   return (long) (Math.random() * 1000);
 }
 public static void main(String[] args) {
   // 阻塞队列,能容纳100个文件
   final BlockingQueue<File> queue = new LinkedBlockingQueue<File>(100);
   // 线程池
   final ExecutorService exec = Executors.newFixedThreadPool(5);
   final File root = new File("D:\\ISO");
   // 完成标志
   final File exitFile = new File("");
   // 原子整型,读个数
   // AtomicInteger可以在并 * 况下达到原子化更新,避免使用了synchronized,而且性能非常高。
   final AtomicInteger rc = new AtomicInteger();
   // 原子整型,写个数
   final AtomicInteger wc = new AtomicInteger();
   // 读线程
   Runnable read = new Runnable() {
     public void run() {
       scanFile(root);
       scanFile(exitFile);
     }
     public void scanFile(File file) {
       if (file.isDirectory()) {
         File[] files = file.listFiles(new FileFilter() {
           public boolean accept(File pathname) {
             return pathname.isDirectory() || pathname.getPath().endsWith(".iso");
           }
         });
         for (File one : files)
           scanFile(one);
       } else {
         try {
           // 原子整型的incrementAndGet方法,以原子方式将当前值加 1,返回更新的值
           int index = rc.incrementAndGet();
           System.out.println("Read0: " + index + " " + file.getPath());
           // 添加到阻塞队列中
           queue.put(file);
         } catch (InterruptedException e) {
         }
       }
     }
   };
   // submit方法提交一个 Runnable 任务用于执行,并返回一个表示该任务的 Future。
   exec.submit(read);
   // 四个写线程
   for (int index = 0; index < 4; index++) {
     // write thread
     final int num = index;
     Runnable write = new Runnable() {
       String threadName = "Write" + num;
       public void run() {
         while (true) {
           try {
             Thread.sleep(randomTime());
             // 原子整型的incrementAndGet方法,以原子方式将当前值加 1,返回更新的值
             int index = wc.incrementAndGet();
             // 获取并移除此队列的头部,在元素变得可用之前一直等待(如果有必要)。
             File file = queue.take();
             // 队列已经无对象
             if (file == exitFile) {
               // 再次添加"标志",以让其他线程正常退出
               queue.put(exitFile);
               break;
             }
             System.out.println(threadName + ": " + index + " " + file.getPath());
           } catch (InterruptedException e) {
           }
         }
       }
     };
     exec.submit(write);
   }
   exec.shutdown();
 }
}

AtomicInteger使用总结

AtomicInteger是在使用非阻塞算法实现并发控制,在一些高并发程序中非常适合,但并不能每一种场景都适合,不同场景要使用使用不同的数值类。

来源:http://blog.csdn.net/u012734441/article/details/51619751

标签:java,atomicinteger
0
投稿

猜你喜欢

  • java实现推箱子小游戏

    2023-02-09 04:57:52
  • Java NIO实例UDP发送接收数据代码分享

    2022-12-03 01:30:37
  • SQL Server中的数据复制到的Access中的函数

    2021-10-05 16:06:42
  • 浅析C#中StringBuilder类的高效及与String的对比

    2022-09-14 15:54:04
  • springboot配置templates直接访问的实现

    2023-01-05 14:22:51
  • MybatisX-Generator自动代码生成插件教程

    2022-01-08 10:50:48
  • C#多线程系列之线程的创建和生命周期

    2023-08-31 17:10:16
  • java 线程创建多线程详解

    2021-08-06 22:02:22
  • C#异步编程由浅入深(一)

    2023-12-16 07:32:29
  • ShardingSphere jdbc集成多数据源的实现步骤

    2023-11-25 07:54:56
  • Java中如何快速构建项目脚手架的实现

    2023-10-30 03:37:50
  • Spring创建Bean的6种方式详解

    2022-07-18 19:10:13
  • SpringBoot选择自有bean优先加载实现方法

    2023-05-21 06:22:39
  • 解决Android调用系统分享给微信,出现分享失败,分享多文件必须为图片格式的问题

    2023-07-03 11:08:04
  • Java ExecutorService四种线程池使用详解

    2023-05-17 07:12:56
  • SpringMVC使用@PathVariable接收参数过程解析

    2021-09-03 20:52:41
  • lambda表达式解决java后台分组排序过程解析

    2023-11-29 06:03:39
  • C#加密解密文件小工具实现代码

    2021-09-21 07:31:41
  • SpringBoot瘦身打包部署的实现

    2021-09-09 16:54:21
  • java用applet画图用到的方法(涉及双缓冲)

    2021-07-09 17:27:32
  • asp之家 软件编程 m.aspxhome.com