Java并发编程- CAS原理
Java并发编程- CAS原理
例子:
/** * CAS原理 * @author wufei * @create 2019-07-23 19:03 **/ public class CAS1 { private static volatile int m =0; //原子性的保证 private static AtomicInteger atomicInteger = new AtomicInteger(0); private static void incress1(){ m ++; } private static void incress2(){ atomicInteger.incrementAndGet(); } public static void main(String[] args) throws InterruptedException{ Thread[] th1 = new Thread[20]; for (int i = 0; i < 20; i++) { th1[i] = new Thread(new Runnable() { public void run() { CAS1.incress1(); } }); th1[i].start(); th1[i].join(); } Thread[] th2 = new Thread[20]; for (int i = 0; i < 20; i++) { th2[i] =new Thread(new Runnable() { public void run() { CAS1.incress2(); } }); th2[i].start(); th2[i].join(); } System.out.println("m: "+m); System.out.println("atomicInteger: "+atomicInteger.get()); } }
运行都是输出20 20
反编译:
javap -v CAS1.class
javap -c CAS1.class
我们查看的只需要incress1()和incress2()