自旋锁(spinlock):
是指尝试获取锁的线程不会立即阻塞,而是采用循环的方式去尝试获取锁,这样的好处是减少线程上下文切换的消耗,缺点是循环会消耗CPU
问题:手写一个自旋锁
题目:实现一个自旋锁
自旋锁好处:循环比较获取直到成功为止,没有类似wait的阻塞
通过CAS操作完成自旋锁,A线程先进来调用myLock方法自己持有锁5秒钟,B随后进来后发现
当前有线程持有锁,不是null,所以只能通过自旋等待,直到A释放锁后B随后抢到。
代码
package Lock;
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() + "\t come in 0(n_n)0");
while (atomicReference.compareAndSet(null,thread)){
}
}
public void myUnlock(){
Thread thread =Thread.currentThread();
atomicReference.compareAndSet(thread,null);
System.out.println(Thread.currentThread().getName() + "\t invoked myUnLock()");
}
public static void main(String[] args) {
SpinLockDemo spinLockDemo =new SpinLockDemo();
new Thread(()->{
spinLockDemo.myLock();
try {
TimeUnit.SECONDS.sleep(5);
}catch (InterruptedException e){e.printStackTrace();}
spinLockDemo.myUnlock();
},"AA").start();
try {
TimeUnit.SECONDS.sleep(3);
}catch (InterruptedException e){e.printStackTrace();}
new Thread(()->{
spinLockDemo.myLock();
spinLockDemo.myUnlock();
},"BB").start();
}
}
AA come in 0(n_n)0
BB come in 0(n_n)0
BB invoked myUnLock()
AA invoked myUnLock()
Process finished with exit code 0