我们这里自己手写了一个自旋锁,就是根据AtomicReference类,比较更新的特性,
加锁:先看atomicReference 是不是 没有值,如果没有就加锁成功,锁为当前线程,如果有,就一直循环。
解锁:就是将atomicReference的值设置为null
自定义一个自旋锁
import java.util.concurrent.atomic.AtomicReference;/*** 自旋锁*/public class SpinlockDemo {// int 0// Thread nullAtomicReference<Thread> atomicReference = new AtomicReference<>();// 加锁public void myLock(){Thread thread = Thread.currentThread();System.out.println(Thread.currentThread().getName() + "==> mylock");// 自旋锁while (!atomicReference.compareAndSet(null,thread)){}}// 解锁public void myUnLock(){Thread thread = Thread.currentThread();System.out.println(Thread.currentThread().getName() + "==> myUnlock");atomicReference.compareAndSet(thread,null);}}
测试自旋
import java.util.concurrent.TimeUnit;import java.util.concurrent.locks.ReentrantLock;public class TestSpinLock {public static void main(String[] args) throws InterruptedException {// ReentrantLock reentrantLock = new ReentrantLock();// reentrantLock.lock();// reentrantLock.unlock();// 底层使用的自旋锁CASSpinlockDemo lock = new SpinlockDemo();new Thread(()-> {lock.myLock();try {TimeUnit.SECONDS.sleep(5);} catch (Exception e) {e.printStackTrace();} finally {lock.myUnLock();}},"T1").start();TimeUnit.SECONDS.sleep(1);new Thread(()-> {lock.myLock();try {TimeUnit.SECONDS.sleep(1);} catch (Exception e) {e.printStackTrace();} finally {lock.myUnLock();}},"T2").start();}}
