Java锁之自旋锁
Java鎖之自旋鎖
目錄
1. java鎖之自旋鎖理論知識
點是循環會消耗CPU
2. java鎖之自旋鎖代碼驗證
代碼驗證:通過CAS操作完成自旋鎖,A線程先進來調用myLock方法自己持有鎖5秒鐘,B隨后進來后發現當前有線程持有鎖,不是null,所以只能通過自旋等待,知道A釋放鎖后B隨后搶到。
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 ");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(1);} catch (InterruptedException e) {e.printStackTrace();}new Thread(() -> {spinLockDemo.myLock();try {TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {e.printStackTrace();}spinLockDemo.myUnlock();},"BB").start();} }編譯結果:
總結
- 上一篇: Java锁之可重入锁和递归锁
- 下一篇: Java并发编程之阻塞队列