AtomicReference,AtomicInteger,AtomicBoolean

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/qq_39507260/article/details/85010584

Atomic Atomic family

Atomic Atomic family guarantees operation under multiple threads is the same object, but at the same time only one thread can be operated to ensure that the latest data when it is operating under a thread.
1. AtomicReference, atomic reference
provides an object for atoms to read and write, to ensure the operation of the multithreaded same object, and synchronized operation.

private static User mUser;

    private void init() {
    	//引用对象mUser
        AtomicReference<User> ar = new AtomicReference<User>(mUser);

        //比较,若target和原子mUser是同一对象,用update替换它。
        ar.compareAndSet(V target, V update);
        //设置为newValue,并返回旧值
        ar.getAndSet(V newValue);
        //最终设置值,不能再变了
        ar.lazySet(V newValue);
        //设置为newValue
        ar.set(V newValue);
        //获取值
        ar.get();
    }

2. AtomicInteger
allows class implements AtomicInteger, this class is itself a AtomicInteger, you can perform various operations on the following categories. Like AtomicLong usage.

private static int count;

    private void init() {
        AtomicInteger ai = new AtomicInteger(count);

        //比较,若target和原子count是同一对象,用update替换它。
        ai.compareAndSet(V target, V update);
        //获取当前,然后设置为newValue
        ai.getAndSet(V newValue);
        //最终设置值,不能再变了
        ai.lazySet(V newValue);
        //设置为newValue
        ai.set(V newValue);
        //获取值
        ai.get();
        //count加上预期值delta,然后获取值
        ai.addAndGet(int delta);
        //获取当前值,然后count加上预期值delta
        ai.getAndAdd(int delta);
        //自增/自减,然后获取值
        ai.incrementAndGet();
        ai.decrementAndGet();
        //获取值,然后自增/自减
        ai.getAndIncrement();
        ai.getAndDecrement();
    }

3. AtomicBoolean
allows class implements AtomicBoolean, this class is itself a AtomicBoolean, you can perform various operations on the following categories.

private static boolean hasValue = false;

    private void init() {
        AtomicBoolean ab = new AtomicBoolean(hasValue);
        //比较,若target和原子count是同一对象,用update替换它。
        ab.compareAndSet(V target, V update);
        //获取当前,然后设置为newValue
        ab.getAndSet(V newValue);
        //最终设置值,不能再变了
        ab.lazySet(V newValue);
        //设置为newValue
        ab.set(V newValue);
        //获取值
        ab.get();
    }

Summing up the first three

Guess you like

Origin blog.csdn.net/qq_39507260/article/details/85010584