利用AtomicReference实现自定义自旋锁。
A 线程先抢占资源,B 线程只能自旋着,等 A 线程释放锁后,B 线程才获取锁,然后释放锁。
/**
* @author xxx
* @descpription: 自定义自旋锁
* @date 2024/6/10
*/
public class SpinLockDemo {
AtomicReference<Thread> atomicReference = new AtomicReference();
public void lock(){
Thread thread = Thread.currentThread();
System.out.println(Thread.currentThread().getName()+ " is waiting to get lock");
while (!atomicReference.compareAndSet(null, thread)) {
// 自旋
}
}
public void unlock(){
Thread thread = Thread.currentThread();
System.out.println(Thread.currentThread().getName()+ " has released the lock");
atomicReference.compareAndSet(thread, null);
}
public static void main(String[] args) {
SpinLockDemo spinLockDemo = new SpinLockDemo();
new Thread(() -> {
spinLockDemo.lock();
try {
TimeUnit.SECONDS.sleep(5);
}catch (InterruptedException e){
e.printStackTrace();
}
spinLockDemo.unlock();
}, "A").start();
try {
TimeUnit.MILLISECONDS.sleep(500);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
new Thread(() -> {
spinLockDemo.lock();
spinLockDemo.unlock();
}, "B").start();
}
}