016 Atomic Class

I. Overview

In our previous counting program, we know that as long as count++ is an atomic operation, the thread safety of the program can be guaranteed.

  Of course, this commonly used function appeared in jdk5, which is the atomic class.

Atomic classes are all atomic under the JUC package, and the number of classes is relatively large.


 

2. Introduction to Atoms

  The operations of atomic classes can be guaranteed to be thread-safe. When using these variables in our application, we need to consider these atomicity.

  The following introduces the use of commonly used atomic classes:

    @Test
    public void test() {
        AtomicInteger value = new AtomicInteger(10);
        System.out.println(value.get());
        value.set(11);
        System.out.println(value.get());
    }

AtomicInteger, we use get() and set() to get and set respectively, these are very simple.

  We want to implement count++ operations like this: 

@Test
    public void test2() {
        AtomicInteger value = new AtomicInteger(10);
        System.out.println(value.incrementAndGet());
    }

  We can easily implement such operations as auto-increment, and we can guarantee that this auto-increment operation is atomic.


 

3. Summary

  Our use of atomic classes is very simple, because it guarantees that our operations on them are atomic.

  When we need to synchronize such a variable, we can consider using such a variable to complete the operation.

    But these are not the most important, the most important is CAS. This is explained below.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325313349&siteId=291194637