public class SpinLockDemo {
//原子引用内存 线程
AtomicReference<Thread> atomicReference=new AtomicReference<>();
public void myLock(){
Thread thread = Thread.currentThread();
;
System.out.println(thread.getName()+"进来了");
//CAS比较并交换,但是容易引发aba问题,这就不再讨论之列
while(!atomicReference.compareAndSet(null,thread)){
//不停轮询,极端消耗cpu资源
}
}
public void unlock(){
Thread thread = Thread.currentThread();
atomicReference.compareAndSet(thread,null);
System.out.println(thread.getName()+"已经离开了");
}
public static void main(String[] args) {
//测试案例
SpinLockDemo spinLockDemo=new SpinLockDemo();
new Thread(()->{
spinLockDemo.myLock();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
spinLockDemo.unlock();
},"AA").start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(()->{
spinLockDemo.myLock();
spinLockDemo.unlock();
},"BB").start();
}
}