手写自旋锁
- 需要AtomicReference类的cas操作
- 加锁方法cas占用则循环,没有就拿到
- 解锁直接置为null就行
- 具体代码有注释
package com.xiaojie.haha;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
public class SpinLock {
AtomicReference<Thread> atomicReference = new AtomicReference<>();
public void MyLock(){
Thread thread = Thread.currentThread();
while (!atomicReference.compareAndSet(null,thread)){
}
System.out.println(Thread.currentThread().getName()+"拿到了MyLock");
}
public void MyUnLock(){
Thread thread = Thread.currentThread();
atomicReference.compareAndSet(thread,null);
System.out.println(Thread.currentThread().getName()+"解锁了MyUnLock");
}
public static void main(String[] args) throws InterruptedException {
SpinLock spinLock = new SpinLock();
new Thread(()->{
spinLock.MyLock();
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
spinLock.MyUnLock();
},"t1").start();
TimeUnit.SECONDS.sleep(1);
new Thread(()->{
spinLock.MyLock();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
spinLock.MyUnLock();
},"t2").start();
}
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/e39e648ae46efa3807c9e85286ccfc3d.jpeg#pic_center)