自旋锁指获取锁的线程不会立即阻塞,而是采用循环的方法去尝试获取锁,这样的好处是减少线程上下文切换的消耗,缺点是消耗CPU
自旋锁的好处是:线程不会阻塞
自旋锁的坏处是:如果长时间不能获得锁,循环重了后,性能会下降
手写自旋锁
/**
* 手写自旋锁
*/
public class SpinLock {
//创建原子引用类型为Thread的对象
AtomicReference<Thread> threadAtomicReference = new AtomicReference<>();
//创建自己的加锁
public void myLock(){
Thread thread = Thread.currentThread();
System.out.println(thread.getName()+"======加锁了");
//如果当前threadAtomicReference还有值,则表示有人还在操作,则会一直循环,到threadAtomicReference为null
while(!threadAtomicReference.compareAndSet(null,thread)){
}
}
//创建自己的解锁
public void myUnLock(){
Thread thread = Thread.currentThread();
System.out.println(thread.getName()+"======解锁了");
//只要是用一个线程才能解锁成功
threadAtomicReference.compareAndSet(thread,null);
}
public static void main(String[] args) {
SpinLock spinLock = new SpinLock();
new Thread(() ->{
spinLock.myLock();
try {TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); }
spinLock.myUnLock();
},"t1").start();
new Thread(() ->{
spinLock.myLock();
try {TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); }
spinLock.myUnLock();
},"t2").start();
}
}