JAVA使用 Atomic,Unsafe实现自旋锁(可重入锁)

JAVA使用 Atomic,Unsafe实现自旋锁(可重入)

自旋锁(spinlock,忙等锁):是指当一个线程在获取锁的时候,如果锁已经被其它线程获取,那么该线程将循环等待,然后不断的判断锁是否能够被成功获取,直到获取到锁才会退出循环,在多线程情况下可能引起CPU升高,甚至导致系统死锁

1.Atomic实现(可重入)


import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicReference;

@Slf4j
public class AtomicLock {
    public static int count = 0;
    AtomicReference<Thread> atomicReference = new AtomicReference<>();

    //加锁
    public void lock() {
        Thread thread = Thread.currentThread();
            //判断当前占有锁的线程是不是该线程
            if (thread == atomicReference.get()) {
                //如果占有,将变量进行++。实现加锁二次
                ++count;
                return;
            }
            //尝试修改默认值加锁,其余线程会一次在此自旋
            while (!atomicReference.compareAndSet(null, thread)) {
            }
    }
    //解锁
    public void unlock() {
        Thread thread = Thread.currentThread();
        if (thread == atomicReference.get()) {
            if (count > 0) {
                //如果变量之前被++,现在--,
                --count;
            } else {
                  //尝试修改默认值解锁
                atomicReference.compareAndSet(thread, null);
            }
        }
    }
    //mian方法测试
    static Integer i = 0;
    public static void main(String[] args) throws InterruptedException {
        ThreadPoolExecutor pool = (ThreadPoolExecutor) Executors.newFixedThreadPool(3);
        AtomicLock atomicLock= new AtomicLock();
        for (int i1 = 0; i1 < 10000; i1++) {
            pool.execute(() -> {
            	//这里加锁二次,解锁二次。如果只解锁一次,会发现i最后的数字会有所变少,
            	//因为其他线程还在自旋没有实现++操作,占用了一次循环次数
                atomicLock.lock();
                atomicLock.lock();
                ++i;
                log.info(Thread.currentThread().getName() + "执行" + i);
                atomicLock.unlock();
                atomicLock.unlock();
            });
        }
        //等待线程池执行完毕,自行设置时间
        Thread.sleep(2000);
        pool.shutdown();
        System.out.println("i = "+i);
    }
}

2.Unsafe实现

Atomic本身就是用Unsafe实现,这里就不补上可重入代码了。一样的判断,参考上面代码

import lombok.extern.slf4j.Slf4j;
import sun.misc.Unsafe;

import java.lang.reflect.Field;

@Slf4j
public class UnsafeLock<V> {
    private static Unsafe unsafe = null;
    private static final long valueOffset;
    private volatile V value;

    static {
        try {
            unsafe = getUnsafeInstance();
            //计算value内存偏移量
            valueOffset = unsafe.objectFieldOffset(UnsafeLock.class.getDeclaredField("value"));
        } catch (Exception ex) {
            throw new Error(ex);
        }
    }
    //通过反射实例化  Unsafe
    private static Unsafe getUnsafeInstance() throws SecurityException,
             NoSuchFieldException, IllegalArgumentException,
             IllegalAccessException {
        Field theUnsafeInstance = Unsafe.class.getDeclaredField("theUnsafe");
        theUnsafeInstance.setAccessible(true);
        return (Unsafe) theUnsafeInstance.get(Unsafe.class);
    }

      //for循环尝试获取锁
    public void lock() {
            while(!unsafe.compareAndSwapObject(this, valueOffset, null,  Thread.currentThread())) {
            }
    }
    public void unlock() {
        unsafe.compareAndSwapObject(this, valueOffset,   Thread.currentThread(),null);
    }
    
    
    
    public    static     int i = 0;
   static UnsafeLock unsafeLock = new UnsafeLock();

    public static void main(String[] args) throws InterruptedException {
        ThreadPoolExecutor cachedThreadPool = (ThreadPoolExecutor) Executors.newFixedThreadPool(3);
        for (int i1 = 0; i1 < 1000; i1++) {
            cachedThreadPool.execute(() -> {
                unsafeLock.lock();
                ++i;
                log.info(Thread.currentThread().getName() + "执行" + i);
                unsafeLock.unlock();
            });
        }

//        Thread.sleep(2000);
//        cachedThreadPool.shutdown();
//        System.out.println(i);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值