文章来源:嗨学网 敏而好学论坛www.piaodoo.com 欢迎大家相互学习

首先看两段代码,一段是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是在使用非阻塞算法实现并发控制,在一些高并发程序中非常适合,但并不能每一种场景都适合,不同场景要使用使用不同的数值类。

以上就是本文关于Java AtomicInteger类的使用方法详解的全部内容,希望对大家有所帮助。感兴趣的朋友可以参阅:java原生序列化和Kryo序列化性能实例对比分析 、关于Java企业级项目开发思想 、Java map存放数组并取出值代码详解 等,有什么问题可以随时留言,小编会及时回复大家。

原文地址是:http://www.piaodoo.com/thread-13234-1-2.html 丝袜控www.txdah.com 131www.buzc.org学习之外可赏心悦目有助更好地学习!

Java AtomicInteger类的使用方法详解_java - JAVA的更多相关文章

  1. Java File 类的使用方法详解

    Java File类的功能非常强大,利用Java基本上可以对文件进行所有的操作.本文将对Java File文件操作类进行详细地分析,并将File类中的常用方法进行简单介绍,有需要的Java开发者可以看 ...

  2. Java File 类的使用方法详解(转)

    转自:http://www.codeceo.com/article/java-file-class.html Java File类的功能非常强大,利用Java基本上可以对文件进行所有的操作.本文将对J ...

  3. Delphi中TStringList类常用属性方法详解

    TStrings是一个抽象类,在实际开发中,是除了基本类型外,应用得最多的. 常规的用法大家都知道,现在来讨论它的一些高级的用法. 先把要讨论的几个属性列出来: 1.CommaText 2.Delim ...

  4. Python的Django框架中forms表单类的使用方法详解

    用户表单是Web端的一项基本功能,大而全的Django框架中自然带有现成的基础form对象,本文就Python的Django框架中forms表单类的使用方法详解. Form表单的功能 自动生成HTML ...

  5. 【Java】equals()与hashCode()方法详解 (转)

    java.lang.Object类中有两个非常重要的方法: 1 2 public boolean equals(Object obj) public int hashCode() Object类是类继 ...

  6. java:数组操作工具类 java.util.Arrays包 主要方法详解

    Arrays类位于Java.util包下,是一个对数组操作的工具类,现将Arrays类中的方法做一个总结(JDK版本:1.6.0_34).Arrays类中的方法可以分为八类: sort(对数组排序) ...

  7. java 中toString()方法详解

    1.toString()方法 Object类具有一个toString()方法,你创建的每个类都会继承该方法.它返回对象的一个String表示,并且对于调试非常有帮助.然而对于默认的toString() ...

  8. Java中hashCode与equal方法详解

    转载自http://blog.csdn.net/jiangwei0910410003/article/details/22739953 Java中的equals方法和hashCode方法是Object ...

  9. Java使用wait() notify()方法操作共享资源详解_java - JAVA

    文章来源:嗨学网 敏而好学论坛www.piaodoo.com 欢迎大家相互学习 Java多个线程共享资源: 1)wait().notify()和notifyAll()方法是本地方法,并且为final方 ...

随机推荐

  1. Sublime Text 3 相关

    Sublime Text 3 相关 Sublime Text 3是款非常实用代码编辑神器,但是想要用任何一款软件,掌握一些快捷键还是很有必要的.. 将Sublime Text 3 添加到右键选项中 打 ...

  2. GO——beego安装及新建项目(一)

    beego简介 Beego是一个快速开发Go应用的http框架,可用于快速开发Api.web及后端服务等各种应用,是一个RESTful框架. beego的架构 Beego由八个独立模块构建,是一个高度 ...

  3. 爬虫4之pyquery

    pyquery 初始化 字符串初始化 from pyquery import PyQuery as pq doc = pq(html)#html为需要处理的内容 #方法与CSS选择器相同 print( ...

  4. react 中 EventEmitter 事件总线机制

    此机制可用于 react 中兄弟组件中的通信 npm install events -S 事件总线: // eventBus.js import {EventEmitter} from 'events ...

  5. 【Angular5】 返回前一页面 go back to previous page

    import { Component, OnInit } from '@angular/core'; import { Router} from '@angular/router'; import { ...

  6. 【Linux 网络编程】字节序和地址装换

    (3)字节序    <1>大端字节序        最高的有效位存储于最低内存地址处,最低有效位存储于最高内存地址处.    <2>小端字节序        最高的有效位存储于 ...

  7. Java Content Repository API 简介 转自(https://www.ibm.com/developerworks/cn/java/j-jcr/)

    Java Content Repository API 简介 1 如果曾经试过开发内容管理应用程序,那么您应当非常清楚在实现内容系统时所遇到的固有难题.这个领地有点支离破碎,许多供应商都有自己的私有仓 ...

  8. Luogu P3942 将军令

    题目 维护每个点子树中最深的没有被覆盖的点(仅计算这条链上的关键点)的距离. 若\(u\)为关键点,则\(d_u=-k-1\). 记录\(mx=\max\limits_{v\in son_u}d_v+ ...

  9. mysql优化--explain关键字

    MySQL性能优化---EXPLAIN 参见:https://blog.csdn.net/jiadajing267/article/details/81269067 参见:https://www.cn ...

  10. kibana报[FORBIDDEN/12/index read-only / allow delete (api)]错误

    一.错误描述 1.在kibana,dev中pose数据,报[FORBIDDEN/12/index read-only / allow delete (api)]错误. 尝试过网上的说的方法一:在kib ...