search
HomeJavajavaTutorialIntroduction to the use of AtomicInteger class in Java

Introduction to the use of AtomicInteger class in Java

Oct 11, 2017 am 10:08 AM
atomicintegerjavaInstructions

这篇文章主要介绍了Java AtomicInteger类的使用方法详解,文中有具体实例代码,具有一定参考价值,需要的朋友可以了解下。

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

The above is the detailed content of Introduction to the use of AtomicInteger class in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Java Application Performance Monitoring (APM) ToolsJava Application Performance Monitoring (APM) ToolsJul 24, 2025 am 03:37 AM

Common JavaAPM tools include NewRelic, DatadogAPM, AppDynamics, SkyWalking, Pinpoint and Prometheus Grafana Micrometer combinations; whether APM is required depends on system lag, complex microservice calls, performance details and optimization requirements; APM should consider deployment methods, learning costs, performance impact, cost and integration capabilities; when using them, you should pay attention to reasonable configuration, sampling rate, alarm rules, and analyze the root cause in combination with code.

Building Reactive Java Applications with RxJavaBuilding Reactive Java Applications with RxJavaJul 24, 2025 am 03:35 AM

1.RxJava is a responsive framework based on observer pattern and functional programming, suitable for handling asynchronous and non-blocking tasks. 2. Core types include Observable, Flowable, Single, etc., which are used to represent different forms of data flow. 3. Data conversion and combination are performed through operators such as map, filter, and flatMap to simplify complex logic. 4. Use Schedulers.io(), Schedulers.computation(), AndroidSchedulers.mainThread() and other schedulers to control thread switching. 5. Specify the data flow start thread through subscribeOn, obse

Implementing a Thread-Safe Singleton in JavaImplementing a Thread-Safe Singleton in JavaJul 24, 2025 am 03:35 AM

When using double check lock to implement lazy loading singletons, the volatile keyword is required to ensure thread visibility and prevent instruction re-arrangement; 2. It is recommended to use static internal classes (BillPugh scheme) to implement thread-safe lazy loading singletons, because the JVM ensures thread safety and no synchronization overhead; 3. If you do not need lazy loading, you can use static constants to implement simple and efficient singletons; 4. When serialization is involved, enumeration method should be used, because it can naturally prevent multiple instance problems caused by reflection and serialization; in summary, general scenarios prefer static internal classes, and serialized scenarios to select enumerations. Both have the advantages of thread safety, high performance and concise code.

Comparing Java, Kotlin, and Scala for Backend DevelopmentComparing Java, Kotlin, and Scala for Backend DevelopmentJul 24, 2025 am 03:33 AM

Kotlinoffersthebestbalanceofbrevityandreadability,Javaisverbosebutpredictable,andScalaisexpressivebutcomplex.2.Scalaexcelsinfunctionalprogrammingwithfullsupportforimmutabilityandadvancedconstructs,KotlinprovidespracticalfunctionalfeatureswithinanOOPf

Managing Dependencies in a Large-Scale Java ProjectManaging Dependencies in a Large-Scale Java ProjectJul 24, 2025 am 03:27 AM

UseMavenorGradleconsistentlywithcentralizedversionmanagementandBOMsforcompatibility.2.Inspectandexcludetransitivedependenciestopreventconflictsandvulnerabilities.3.EnforceversionconsistencyusingtoolslikeMavenEnforcerPluginandautomateupdateswithDepend

Mastering Java 8 Streams and LambdasMastering Java 8 Streams and LambdasJul 24, 2025 am 03:26 AM

The two core features of Java8 are Lambda expressions and StreamsAPI, which make the code more concise and support functional programming. 1. Lambda expressions are used to simplify the implementation of functional interfaces. The syntax is (parameters)->expression or (parameters)->{statements;}, for example (a,b)->a.getAge()-b.getAge() instead of anonymous internal classes; references such as System.out::println can further simplify the code. 2.StreamsAPI provides a declarative data processing pipeline, the basic process is: create Strea

Java Security Tokenization and EncryptionJava Security Tokenization and EncryptionJul 24, 2025 am 03:24 AM

SecurityToken is used in Java applications for authentication and authorization, encapsulating user information through Tokenization to achieve stateless authentication. 1. Use the jjwt library to generate JWT, select the HS256 or RS256 signature algorithm and set the expiration time; 2. Token is used for authentication, Encryption is used for data protection, sensitive data should be encrypted using AES or RSA, and passwords should be stored with hash salt; 3. Security precautions include avoiding none signatures, setting the expiration time of tokens, using HTTPS and HttpOnlyCookies to store tokens; 4. In actual development, it is recommended to combine SpringSecurity and

The role of `var` for Local-Variable Type Inference in JavaThe role of `var` for Local-Variable Type Inference in JavaJul 24, 2025 am 03:23 AM

var was introduced in Java 10 for local variable type inference, to determine the type during compilation, and maintain static type safety; 2. It can only be used for local variables in methods with initialized expressions, and cannot be used for fields, parameters or return types; 3. Non-initialization, null initialization and lambda expression initialization are prohibited; 4. It is recommended to use them when the type is obvious to improve simplicity and avoid scenarios that reduce readability. For example, types should be explicitly declared when complex methods are called.

See all articles

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment