自旋锁是指尝试获取锁的线程不会立即阻塞,而是采用循环的方式去尝试获取锁,这样的好处是减少线程上下文切换的消耗,缺点是循环会消耗CPU。总是看一些理论没有深入去理解,很容易忘记。
例子:
/**
* 项目名:
* Created by fu.
* Created at 2020/12/18
* 描述:自旋锁的实现
*/
public class SpinLockDemo {
//原子引用线程
AtomicReference<Thread> atomicReference = new AtomicReference<>();
public void myLock(){
Thread thread = Thread.currentThread();
System.out.println(Thread.currentThread().getName()+"come in");
while (!atomicReference.compareAndSet(null,thread)){
}
}
public void myUnLock(){
//解锁给下一个线程用
Thread thread = Thread.currentThread();
atomicReference.compareAndSet(thread,null);
System.out.println(Thread.currentThread().getName()+"incoked 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();
},"ta").start();
//暂停一段时间线程
try {
TimeUnit.SECONDS.sleep(1);
}catch (InterruptedException e){
e.printStackTrace();
}
new Thread(()->{
spinLockDemo.myLock();
//暂停一段时间线程
try {
TimeUnit.SECONDS.sleep(1);
}catch (InterruptedException e){
e.printStackTrace();
}
spinLockDemo.myUnLock();
},"nb").start();
}
}