以下代码只在运行结束后打印结果
- public class Test1 {
- private static int a = 0;
- public static void main(String[] args) throws InterruptedException{
- System.err.println("LOL");
- int n=500000;
- while(n-->0){
- startAdd();
- }
- Thread.sleep(2000);
- System.err.println(a);
- }
- public static void startAdd(){
- new Thread(new Runnable() {
- @Override
- public void run() {
- a++;
- }
- }).start();
- }
- }
运行了5次结果
499980
499984
499982
499973
499989
而如果用AtomicInteger
- public class Test2 {
- private static AtomicInteger a = new AtomicInteger(0);
- public static void main(String[] args) throws InterruptedException{
- System.err.println("LOL");
- int n=500000;
- while(n-->0){
- startAdd();
- }
- Thread.sleep(2000);
- System.err.println(a);
- }
- public static void startAdd(){
- new Thread(new Runnable() {
- @Override
- public void run() {
- a.getAndIncrement();
- }
- }).start();
- }
- }
500000
500000
500000
500000
还是500000
懂了吧