自旋锁spinlock自定义自旋锁测试实例package com.sw.lock; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; /** * @Author suaxi * @Date 2021/2/22 23:21 * 自定义自旋锁 */ public class SpinLockTest { AtomicReference<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); } //测试 public static void main(String[] args) throws InterruptedException { SpinLockTest lock = new SpinLockTest(); new Thread(() -> { lock.myLock(); try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.myUnlock(); } }, "A").start(); TimeUnit.SECONDS.sleep(2); new Thread(() -> { lock.myLock(); try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.myUnlock(); } }, "B").start(); /* 执行结果为： A--->myLock() B--->myLock() A--->myUnlock() B--->myUnlock() */ } }