package com.pimee.lock;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
/**
* 自旋锁
*/
public class SpinLockDemo {
// 共享
AtomicReference<Thread> atomicReference = new AtomicReference<>();
/**
* 加锁
*/
public void lock(){
Thread thread = Thread.currentThread();
System.out.println(thread.getName() + " 进入获取锁");
while(!atomicReference.compareAndSet(null, thread)){
System.out.println(thread.getName() + " 自旋等待");
}
}
/**
* 释放锁
*/
public void unlock(){
Thread thread = Thread.currentThread();
System.out.println(thread.getName() + " 进入释放锁");
while(!atomicReference.compareAndSet(thread, null)){
System.out.println(thread.getName() + " 自旋释放锁");
}
System.out.println(thread.getName() + "释放锁成功,退出");
}
public static void main(String[] args) throws InterruptedException {
SpinLockDemo lock = new SpinLockDemo();
// 线程1
new Thread(()->{
lock.lock();
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}, "T1").start();
TimeUnit.SECONDS.sleep(1);
// 线程2
new Thread(()->{
try {
lock.lock();
}finally {
lock.unlock();
}
}, "T2").start();
}
}
结果输出:
T1 进入获取锁
T2 进入获取锁
T1 进入释放锁
T1释放锁成功,退出
T2 进入释放锁
T2释放锁成功,退出