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();
}
spinLockDemo.unlock();
},"t1").start();
try {
TimeUnit.SECONDS.sleep(1);
}catch (InterruptedException e){
e.printStackTrace();
}
new Thread(()->{
spinLockDemo.mylock();
spinLockDemo.unlock();
},"t2").start();
}
}
自旋锁代码实现
最新推荐文章于 2024-09-29 10:25:17 发布
本文介绍了如何在Java中使用AtomicReference实现自旋锁。通过示例代码展示了自旋锁的`mylock()`和`unlock()`方法,以及在一个多线程环境中如何应用自旋锁来保证线程安全。
1071

被折叠的 条评论
为什么被折叠?



