自旋锁的定义:当一个线程尝试去获取某一把锁的时候,如果这个锁此时已经被别人获取(占用),那么此线程就无法获取到这把锁,该线程将会等待,间隔一段时间后会再次尝试获取。这种采用循环加锁 -> 等待的机制被称为自旋锁(spinlock)。看完你就明白的锁系列之自旋锁
java.util.concurrent.atomic.AtomicStampedReference:AtomicStampedReference维护一个对象引用以及一个整数“标记”,可以原子方式更新。
package lock; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicStampedReference; /** * @Author 夏秋初 * @Date 2022/3/5 11:51 */ public class SpinLock { public static AtomicStampedReference<Thread> atomicStampedReference = new AtomicStampedReference(null, 0); /** * 自旋锁的简单实现 */ public static void lock(){ while (!atomicStampedReference.compareAndSet(null, Thread.currentThread(), 0, 1)){ } System.out.println(Thread.currentThread().getName() + "加锁成功"); } public static void unLock(){ System.out.println(Thread.currentThread().getName() + "解锁成功"); atomicStampedReference.compareAndSet( Thread.currentThread(), null, 1, 0); } public static void main(String[] args) { new Thread(()->{ SpinLock.lock(); try{ try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } }finally { SpinLock.unLock(); } },"A").start(); new Thread(()->{ SpinLock.lock(); try{ try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } }finally { SpinLock.unLock(); } },"B").start(); } }