首页 > 代码库 > 自己利用unsafe的cas实现的AtomicInteger

自己利用unsafe的cas实现的AtomicInteger

package com.thinkgem.jeesite.test;

import org.junit.Test;
import sun.misc.Unsafe;

/**
 * Created by zhuangyan on 2016/12/8 0008.
 */

import java.lang.reflect.Field;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
public   class transationTest   {
    private static  String ready ="sdfassdf";
    private      volatile  int   numberValue=http://www.mamicode.com/0;"numberValue"));
        } catch (Exception ex) { throw new Error(ex); }
    }

    //利用反射方式拿到 unsafe 不然会包Security错误,
    public static Unsafe getUnsafe() {
        try {
            Field f = Unsafe.class.getDeclaredField("theUnsafe");
            f.setAccessible(true);
            return (Unsafe)f.get(null);
        } catch (Exception e) {
       /* ... */
            return  null;
        }
    }

    private   class ReaderThread extends Thread {


        @Override
        public   synchronized void run() {
           for(int i=1;i<=2000;i++){
               System.out.println(Thread.currentThread()+ " :" + numberValue);
            // number =   number + 1;
             //  numberValue =   http://www.mamicode.com/numberValue + 1;" :" +numberValue);
            }

        }
    }

    //cast ++
    public    int casTest( int except){
        for(;;){
            int currNum = numberValue;
            int tmpNumber = numberValue + 1;

            //cas 如果currnum 等于当前值(valueOffset指定了值),则更新当前值为tmpNumber
            if(unsafe.compareAndSwapInt(this,valueOffset,currNum,tmpNumber)){
                System.out.println(Thread.currentThread()+ " iudddfifififtmp:" + tmpNumber);
                return tmpNumber;
            }
        }
    }

    public  void mainTest() {
        System.out.println("begin");
        for(int i=1;i<=50;i++){
            Thread Re = new ReaderThread();
            Re.start();

        }

        System.out.println("1249");
    }
}

--------------

测试方法代码

package com.thinkgem.jeesite.test;

import org.junit.*;

/**
 * Created by Administrator on 2017/2/19 0019.
 */
public class junitTest {
    @org.junit.Test
    public void Test() throws InterruptedException {
        System.out.println("tst");
           transationTest tt = new transationTest();

       tt.mainTest();
        Thread.sleep(15000);

    };
}

  利用cas来实现了一个累加多线程方法,用于理解cas原理以及unsafe方法的swap使用

自己利用unsafe的cas实现的AtomicInteger