蘇阿細 - 自定义自旋锁
type: channel
link: https://www.wangchouchou.com/tag/%E8%87%AA%E5%AE%9A%E4%B9%89%E8%87%AA%E6%97%8B%E9%94%81/
items: 自旋锁

自旋锁
type: item
date: 2021-02-22T16:09:00+00:00
description: 自旋锁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() */ } }