package com.xiang.lock; import java.sql.Time; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; public class SpinLockDemo { AtomicReference<Thread> atomicReference = new AtomicReference<>(); public void mylock(){ Thread thread = Thread.currentThread(); System.out.println(thread.getName() + "进来获取锁了"); while (!atomicReference.compareAndSet(null,thread)){ } } public void unlock(){ Thread thread = Thread.currentThread(); atomicReference.compareAndSet(thread,null); System.out.println(thread.getName()+ " 释放锁"); } public static void main(String[] args) { SpinLockDemo spinLockDemo = new SpinLockDemo(); new Thread(()->{ spinLockDemo.mylock(); try { TimeUnit.SECONDS.sleep(10); }catch (InterruptedException e){ e.printStackTrace();
自旋锁代码实现
最新推荐文章于 2024-04-23 02:47:17 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)