[原子类AtomicInteger] 1.getAndAdd(x)实现添加任意值 getAndIncrement()实现i++ 2.compareAndSet实现比较操作

 1)添加数值

package org.example.testatomic;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        AtomicInteger atomicNum = new AtomicInteger(0);

        final int[] num = {0};
        for (int i = 0; i < 1000; i++) {
            new Thread() {
                @Override
                public void run() {
                    for (int j = 0; j < 10000; j++) {
                        /***这个是可以*/
                        atomicNum.getAndAdd(1); // 可以传入任何参数

                        // 不行
//                        atomicNum.set(atomicNum.get() + 1); //
                        // 不行
                        num[0] += 1;
                    }
                }
            }.start();
        }

        TimeUnit.SECONDS.sleep(2);
        System.out.println(atomicNum.get());
        System.out.println(num[0]);
    }
}


/*
10000000
8840106
 */

2)比较操作

package org.example.testFor;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public class Main {
    public static void main(String[] args) {
        AtomicInteger atomicNum = new AtomicInteger(0);
        if (atomicNum.compareAndSet(0, 10)) {
            log.info("exec");
        }

        log.info("{}", atomicNum.get());
    }
}

/*
2022-02-09 18:10:54 [INFO ] [main] org.example.testFor.Main.main(Main.java:12) - exec
2022-02-09 18:10:54 [INFO ] [main] org.example.testFor.Main.main(Main.java:15) - 10
 */

你可能感兴趣的:(#,java多线程,java,蓝桥杯,开发语言)