import java.util.concurrent.atomic.AtomicReference;
/**
* @Author: wz
* @Date: 2022/7/12 23:51
* 自旋锁
*/
public class SpinlockDemo {
// int 0 Thread null
AtomicReference<Thread> atomicReference = new AtomicReference<>();
// 加锁
public void myLock(){
Thread thread = Thread.currentThread();
System.out.println(Thread.currentThread().getName()+"--> mylock");
// 自旋锁
while (!atomicReference.compareAndSet(null, thread)){
}
}
// 解锁
public void myUnLock(){
Thread thread = Thread.currentThread();
System.out.println(Thread.currentThread().getName()+"--> myUnlock");
atomicReference.compareAndSet(thread, null);
}
}
/**
* @Author: wz
* @Date: 2022/7/13 0:00
*/
public class TestSpinLock {
public static void main(String[] args) throws InterruptedException {
SpinlockDemo lock = new SpinlockDemo();
new Thread(() -> {
lock.myLock();
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.myUnLock();
}
}, "A").start();
Thread.sleep(1000);
new Thread(() -> {
lock.myLock();
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.myUnLock();
}
}, "B").start();
}
}