有两个关键点 1、AtomicReference 原子类里面使用了volatile关键字,所以被修饰的属性都具有可见性。因此在不同的线程中修改了变量后,写会主内存的时候。其他线程也会看见。
2、AtomicReference的compareAndSet方法 如果返回true 就说明给对象赋值了。
--------------------------------------------------
public class SpinLockDemo {
AtomicReference<Thread> threadAtomicReference =new AtomicReference<>();
public void lock(){
Thread thread = Thread.currentThread();
System.out.println(thread.getName()+"加锁");
while (!threadAtomicReference.compareAndSet(null,thread)){
System.out.println(thread.getName()+"自旋");
}
}
public void unlock(){
Thread thread = Thread.currentThread();
System.out.println(thread.getName()+"解锁");
threadAtomicReference.compareAndSet(thread,null);
}
public static void main(String[] args) throws InterruptedException {
SpinLockDemo spinLockDemo = new SpinLockDemo();
new Thread(()->{
spinLockDemo.lock();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
spinLockDemo.unlock();
},"AA").start();
Thread.sleep(1000);
new Thread(()->{
spinLockDemo.lock();
spinLockDemo.unlock();
},"BB").start();
}
}