package com.example.demo.morethread;
import java.util.concurrent.atomic.AtomicInteger;
public class AtomicTest {
private static AtomicInteger atomicInteger=new AtomicInteger(0);
private static volatile int num=0;
public static void inc(){
try {
System.out.println(Thread.currentThread().getName()+":线程开始");
Thread.sleep(1);
atomicInteger.getAndIncrement();
System.out.println(Thread.currentThread().getName()+":"+atomicInteger.get());
System.out.println(Thread.currentThread().getName()+":线程结束");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void inc1(){
try {
System.out.println(Thread.currentThread().getName()+":线程开始");
Thread.sleep(1);
num++;
System.out.println(Thread.currentThread().getName()+":"+num);
System.out.println(Thread.currentThread().getName()+":线程结束");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws InterruptedException {
// for (int i=0;i<1000;i++){
// new Thread(()->{AtomicTest.inc();},"thread"+i).start();
// }
// Thread.sleep(4000);
// System.out.println(Thread.currentThread().getName()+":"+atomicInteger.get());
for (int i=0;i<1000;i++){
new Thread(()->{AtomicTest.inc1();},"thread"+i).start();
}
Thread.sleep(4000);
System.out.println(Thread.currentThread().getName()+":"+num);
}
}
执行结果如下:
如果对num的操作是原子级别的,最后输出的结果应该为main:1000,而在执行上面积代码时,很多时侯输出的n都小于1000,这说明num++不是原子级别的操作。原因是声明为volatile的简单变量如果当前值由该变量以前的值相关,那么volatile关键字不起作用,也就是说如下的表达式都不是原子操作: