自己利用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=0;

    private static final Unsafe unsafe = getUnsafe();
    private static final long valueOffset;
    private     long test;
    static {


        try {
            //利用反射获取值地址
            valueOffset = unsafe.objectFieldOffset
                    (transationTest.class.getDeclaredField("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 =   numberValue + 1;
                casTest(1);
   //            ttt(0);

               System.out.println(Thread.currentThread()+ " :" +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使用

posted on 2017-02-19 23:43  zhuanagyan  阅读(324)  评论(0编辑  收藏  举报

导航