1、是指试图获得锁的线程不会堵塞,而是通过循环获得锁。
2、优点:减少上下文切换的消耗。
缺点:循环消耗cpu。
实例
public class reentrantspinlock { private atomicreference<thread> owner = new atomicreference<>(); // 可重入次数 private int count = 0; // 加锁 public void lock() { thread current = thread.currentthread(); if (owner.get() == current) { count++; return; } while (!owner.compareandset(null, current)) { system.out.println(--我在自旋--); } } //解锁 public void unlock() { thread current = thread.currentthread(); //只有持有锁的线程才能解锁 if (owner.get() == current) { if (count > 0) { count--; } else { //此处无需cas操作,因为没有竞争,因为只有线程持有者才能解锁 owner.set(null); } } } public static void main(string[] args) { reentrantspinlock spinlock = new reentrantspinlock(); runnable runnable = () -> { system.out.println(thread.currentthread().getname() + 开始尝试获取自旋锁); spinlock.lock(); try { system.out.println(thread.currentthread().getname() + 获取到了自旋锁); thread.sleep(4000); } catch (interruptedexception e) { e.printstacktrace(); } finally { spinlock.unlock(); system.out.println(thread.currentthread().getname() + 释放了了自旋锁); } }; thread thread1 = new thread(runnable); thread thread2 = new thread(runnable); thread1.start(); thread2.start(); }}
以上就是java怎么实现可重入的自旋锁的详细内容。