AtomicInteger 中 incrementAndGet与getAndIncrement 两个方法的区别

源码:

getAndIncrement:
public final int getAndIncrement() {
       for (;;) {
              int current = get();
              int next = current + 1;
              if (compareAndSet(current, next))
                  return current;
       }
}
incrementAndGet:
public final int incrementAndGet() {
     for (;;) {
         int current = get();
         int next = current + 1;
         if (compareAndSet(current, next))
             return next;
    }
}

通过代码可以看出:

getAndIncrement返回的是当前值;

incrementAndGet返回的是加1后的值。

下面补充下AtomicInteger类使用方法:


AtomicInteger的使用(高并发)

普通代码处理高并发,对count进行++操作:

public class MyAtomicInteger {
    private static final Integer threadCount = 20;
    private static Integer num = 0;
    private static void increase() {
        num++;
    }

    public static void main(String[] args) {
        Thread[] threads = new Thread[threadCount];
        for (int i = 0; i < threadCount; i++) {
            threads[i] = new Thread(() -> {
                for (int i1 = 0; i1 < 2000; i1++) {
                    increase();
                }
            });
            threads[i].start();
        }
        while (Thread.activeCount() > 1) {
//            意思就是调用yield方法会让当前线程交出CPU权限,让CPU去执行其他的线程。它跟sleep方法类似,同样不会释放锁。
//            但是yield不能控制具体的交出CPU的时间,另外,yield方法只能让拥有相同优先级的线程有获取CPU执行时间的机会。
//            注意调用yield方法并不会让线程进入阻塞状态,而是让线程重回就绪状态,它只需要等待重新获取CPU执行时间,这一点是和sleep方法不一样的
            Thread.yield();
        }
        System.out.println(Thread.currentThread().getName());
        System.out.println("num:" + num);
    }
}

运行结果如下:

main
num:36939

正确值应该是40000,但是少了,说明我们的代码有问题
加上volatile修饰count:

public class MyAtomicInteger {
    private static final Integer threadCount = 20;
    private static volatile Integer num = 0;
    private static void increase() {
        num++;
    }

    public static void main(String[] args) {
        Thread[] threads = new Thread[threadCount];
        for (int i = 0; i < threadCount; i++) {
            threads[i] = new Thread(() -> {
                for (int i1 = 0; i1 < 2000; i1++) {
                    increase();
                }
            });
            threads[i].start();
        }
        while (Thread.activeCount() > 1) {
//            意思就是调用yield方法会让当前线程交出CPU权限,让CPU去执行其他的线程。它跟sleep方法类似,同样不会释放锁。
//            但是yield不能控制具体的交出CPU的时间,另外,yield方法只能让拥有相同优先级的线程有获取CPU执行时间的机会。
//            注意调用yield方法并不会让线程进入阻塞状态,而是让线程重回就绪状态,它只需要等待重新获取CPU执行时间,这一点是和sleep方法不一样的
            Thread.yield();
        }
        System.out.println(Thread.currentThread().getName());
        System.out.println("num:" + num);
    }
}

结果还是差强人意,结果如下:

main
num:39490

这个时候引入java并发包下的AtomicInteger类,利用其原子操作实现高并发问题解决,代码如下:

public class MyAtomicInteger {
    private static final Integer threadCount = 20;
    private static AtomicInteger count = new AtomicInteger(0);
    private static void increase() {
        count.incrementAndGet();
    }

    public static void main(String[] args) {
        Thread[] threads = new Thread[threadCount];
        for (int i = 0; i < threadCount; i++) {
            threads[i] = new Thread(() -> {
                for (int i1 = 0; i1 < 2000; i1++) {
                    increase();
                }
            });
            threads[i].start();
        }
        while (Thread.activeCount() > 1) {
//            意思就是调用yield方法会让当前线程交出CPU权限,让CPU去执行其他的线程。它跟sleep方法类似,同样不会释放锁。
//            但是yield不能控制具体的交出CPU的时间,另外,yield方法只能让拥有相同优先级的线程有获取CPU执行时间的机会。
//            注意调用yield方法并不会让线程进入阻塞状态,而是让线程重回就绪状态,它只需要等待重新获取CPU执行时间,这一点是和sleep方法不一样的
            Thread.yield();
        }
        System.out.println(Thread.currentThread().getName());
        System.out.println("num:" + count);
    }
}

运行结果:

main
num:40000

可见实现了对高并发情况下问题的解决!

实现原理:
利用cas原理,在主存中有一V值,线程在进入的时候会获取到V值,在进行更新的时候,会把自己获取到的V值和主存的V值进行比较,如果相等就进行更新操作,然后返回V的旧值,避免重复更新操作。同时和之前线程同时进来的线程获取的V值就不等于之前线程更新后主存中的V值了,就不能实现更新操作。但是,会利用while循环
while(!this.compareAndSwapInt(var1, var2, var5, var5 + var4)); 不断地把主存中的V值更新成自己的V值,当相等的时候,实现更新操作,从而解决高并发问题。这就是无锁环境下的并发控制,效率高于qas锁,称为乐观锁。。

posted @ 2020-10-29 17:15  47号Gamer丶  阅读(864)  评论(0编辑  收藏  举报