public class SpinTest { // 创建原子引用类 AtomicReference<Thread> atomicReference = new AtomicReference<>(); // 获取锁 public void myLock() { // 获取当前线程 Thread thread = Thread.currentThread(); while (!atomicReference.compareAndSet(null,thread)){ } System.out.println(thread.getName() + "上锁"); } // 解锁 public void myUnLock () { Thread thread = Thread.currentThread(); atomicReference.compareAndSet(thread, null); System.out.println(thread.getName() + " 解锁"); } public static void main(String[] args) { SpinTest zixuan = new SpinTest(); new Thread(() -> { zixuan.myLock(); ThreadUtil.sleep(5, TimeUnit.SECONDS); zixuan.myUnLock(); }, "t1").start(); ThreadUtil.sleep(1, TimeUnit.SECONDS); new Thread(() -> { zixuan.myLock(); ThreadUtil.sleep(1, TimeUnit.SECONDS); zixuan.myUnLock(); }, "t2").start(); } }
利用juc原子引用类手动实现自旋锁
最新推荐文章于 2024-06-12 11:59:04 发布