java中怎么实现可重入的自旋锁
作者:SunnyJourney
时间:2023-04-25
来源:互联网
浏览:0
说明1、是指试图获得锁的线程不会堵塞,而是通过循环获得锁。2、优点:减少上下文切换的消耗。缺点:循环消耗CPU。实例publicclassReentrantSpinLock{privateAtomicReferenceowner=newAtomicReference();//可重入次数privateintcount=0;//加锁publicvoidlock(){Threadcurrent=Thread.currentThread();if(owner.get()==current){count++;ret
说明
1、是指试图获得锁的线程不会堵塞,而是通过循环获得锁。
2、优点:减少上下文切换的消耗。
缺点:循环消耗CPU。
实例
public class ReentrantSpinLock {
private AtomicReference owner = new AtomicReference<>();
// 可重入次数
private int count = 0;
// 加锁
public void lock() {
Thread current = Thread.currentThread();
if (owner.get() == current) {
count++;
return;
}
while (!owner.compareAndSet(null, current)) {
System.out.println("--我在自旋--");
}
}
//解锁
public void unLock() {
Thread current = Thread.currentThread();
//只有持有锁的线程才能解锁
if (owner.get() == current) {
if (count > 0) {
count--;
} else {
//此处无需CAS操作,因为没有竞争,因为只有线程持有者才能解锁
owner.set(null);
}
}
}
public static void main(String[] args) {
ReentrantSpinLock spinLock = new ReentrantSpinLock();
Runnable runnable = () -> {
System.out.println(Thread.currentThread().getName() + "开始尝试获取自旋锁");
spinLock.lock();
try {
System.out.println(Thread.currentThread().getName() + "获取到了自旋锁");
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
spinLock.unLock();
System.out.println(Thread.currentThread().getName() + "释放了了自旋锁");
}
};
Thread thread1 = new Thread(runnable);
Thread thread2 = new Thread(runnable);
thread1.start();
thread2.start();
}
}
作者最新文章
图几
2026-09-16 17:43
SQL中ROUND函数对0.5的处理机制及强制四舍五入方法
2026-09-15 14:19
JS金额计算怎么避免四舍五入误差
2026-09-14 17:32
韩国8月携号转网数据:Galaxy Z8系列iPhone用户转化率约为Z7系列2倍
2026-09-08 17:02
AE基础教程:如何创建合成并制作关键帧动画
2026-09-04 09:27
上一篇:
java怎么创建接口实现类
热门文章
更多
精品专题
更多
Mac软件
更多
WINDOWS
更多
Windows 10
Windows
Windows 10 是一款微软推出的经典操作系统,拥有硬件兼容性与多任务处理能力。它更偏向把系统状态查看和常用调节动作放在一起,适合需要持续观察和微调设备状态的场景。
极度公式
Windows/macOS/Linux
极度公式是一款跨平台专业LaTeX公式识别编辑软件,支持OCR公式识别和多平台编辑。和使用说明,避免使用,享受完整功能与稳定支持。做扫描整理、文字提取和表格转换时,它能把识别后的处理步骤接得更顺,资料录入这类场景会省下不少时间。
















