什么为自旋锁?
自旋锁是指尝试获取的线程不会立即阻塞,而是采用循环的方式去尝试获取锁,这样的好处是减少线程上下文切换的消耗,缺点是玄幻会消耗CPU
先来看一下代码:
import java.sql.Time;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
/**
* 自旋锁
*/
public class SpinLockDemo {
AtomicReference<Thread> atomicReference = new AtomicReference<>();
public void mylock(){
Thread thread = Thread.currentThread();
System.out.println(Thread.currentThread().getName() + "come in O(∩_∩)O哈哈~");
while (!atomicReference.compareAndSet(null,thread)){
}
}
public void myUnlock(){
Thread thread = Thread.currentThread();
atomicReference.compareAndSet(thread,null);
System.out.println(Thread.currentThread().getName() +"invoked myUnLock()");
}
public static void main(String[] args) {
SpinLockDemo spinLockDemo = new SpinLockDemo();
//a
new Thread(() -> {
spinLockDemo.mylock();
try{
TimeUnit.SECONDS.sleep(5);
}catch (InterruptedException e){e.printStackTrace();}
spinLockDemo.myUnlock();
},"AA").start();
try {
TimeUnit.SECONDS.sleep(1);
}catch (InterruptedException e ){e.printStackTrace();}
//b
new Thread(() -> {
spinLockDemo.mylock();
try{
TimeUnit.SECONDS.sleep(5);
}catch (InterruptedException e){e.printStackTrace();}
spinLockDemo.myUnlock();
},"BB").start();
}
}
自旋锁的标志就是这段
while (!atomicReference.compareAndSet(null,thread)){
}
什么意思呢? 我的理解是,当一个线程一直在使用当中,写一个循环判断,当这段线程为null的时候便可使用,那么这个就是自旋锁的原理
执行这段代码,打印出来的为
A执行完5秒钟后,B才能执行.这便是自旋锁的作用;