package wetalk.build.threadSafe.juc;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
/**
* 自旋锁
*/
public class SpinLock {private AtomicReference atomicReference = new AtomicReference<>();
public void lock() {
final Thread thread = Thread.currentThread();
while (!atomicReference.compareAndSet(null, thread)) ;
}public void unlock() {
final Thread thread = Thread.currentThread();
while (!atomicReference.compareAndSet(thread, null)) ;
}public static void main(String[] args) {
SpinLock spinLock = new SpinLock();
new Thread(() -> {
try {
spinLock.lock();
System.out.println("t1 start to execute");
TimeUnit.SECONDS.sleep(50);
System.out.println("t1 execute success");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
spinLock.unlock();
}
}, "t1").start();
try {
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}new Thread(() -> {
try {
spinLock.lock();
System.out.println("t2 start to execute");
TimeUnit.SECONDS.sleep(10);
System.out.println("t2 execute success");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
spinLock.unlock();
}
}, "t2").start();
}
}
【自旋锁简单实现】自旋锁简单实现
推荐阅读
- 笔记|如何在Windows11安装安卓子系统()
- 笔记|C语言数据结构——二叉树的顺序存储和二叉树的遍历
- 2021年下半年《信息系统项目管理师》真题
- 个人理解|【C语言基础之类型转换】
- 学习分享|【C语言函数基础】
- 个人理解|【C语言实现井字棋及电脑落子优化】
- Python|蓝桥杯 平面切割 Python
- Python|Python 每日一练 二分查找 搜索旋转排序数组 详解
- 笔记|这是一个关于face_recognition和dlib库的安装(亲测有用,毕竟我代码都写出来了)
- 信令模式与非信令模式