用了AtomicReference原子引用和CAS
package com.suo8;
import java.sql.Time;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
/**
* @author QLBF
* @version 1.0
* @date 2021/5/23 15:22
*/
class SpinlockDemo{
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()+"==> muUnlock");
atomicReference.compareAndSet(thread,null);
}
}
public class TestSpinLock {
public static void main(String[] args) throws InterruptedException {
// 底层使用的自旋锁CAS
SpinlockDemo spinlockDemo=new SpinlockDemo();
new Thread(()->{
spinlockDemo.myLock();
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
spinlockDemo.myUnLock();
}
},"T1").start();
TimeUnit.SECONDS.sleep(1);
new Thread(()->{
spinlockDemo.myLock();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
spinlockDemo.myUnLock();
}
},"T2").start();
}
}
这里因为开始不是类似synchronized那么强烈,所以他俩都会进去(不会的,可以去看八锁现象)
T1进来是拿到锁,是期望的null,变成thread,这时候线程T2拿到锁后是thraed开始自旋,等待T1解锁变回null,T2才能走出自旋(只有T2自旋)