手撕自旋锁

自旋锁是指尝试获取锁的线程不会因为获取锁失败而阻塞,而是采用循环的方式去尝试获取锁,也就是说用循环替代了阻塞,好处是减少线程上下文切换的消耗,缺点是会消耗CPU
 1 /*手撕自旋锁*/
 2 public class SpinLock {
 3     AtomicReference<Thread> atomicReference = new AtomicReference<>();
 4     public void lock(){
 5         Thread thread = Thread.currentThread();
 6         while (!atomicReference.compareAndSet(null,thread)){
 7         }
 8     }
 9     public void unlock(){
10         Thread thread = Thread.currentThread();
11         atomicReference.compareAndSet(thread,null);
12     }
13 }

 

posted @ 2022-03-11 01:02  独醉乄  阅读(28)  评论(0)    收藏  举报