自旋锁
自旋锁
首次接触到自旋锁是在AtomicInteger类,其中的GetAndIncrement()方法,是类似于num++的原子性操作。
源码分析:其中的do while就是一个自旋锁
public final int getAndIncrement() {
    return unsafe.getAndAddInt(this, valueOffset, 1);
}
public final int getAndAddInt(Object o, long offset, int delta) {
    int v;
    do {
        v = getIntVolatile(o, offset);
    } while (!compareAndSwapInt(o, offset, v, v + delta));
    return v;
}
自旋锁的定义
自旋锁是计算机科学用于多线程同步的一种锁,线程反复检查锁变量是否可用。由于线程在这一过程中保持执行,因此是一种忙等待。一旦获取了自旋锁,线程会一直保持该锁,直至显式释放自旋锁。
自己写的一个自旋锁的例子
package juc;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
public class TestSpinLock {
    private AtomicReference<Thread> aft = new AtomicReference<>();
    public static void main(String[] args) throws InterruptedException {
        TestSpinLock testSpinLock = new TestSpinLock();
        new Thread(()->{
            testSpinLock.myLock();
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            testSpinLock.myUnLock();
        },"A").start();
        TimeUnit.SECONDS.sleep(1);
        new Thread(()->{
            testSpinLock.myLock();
            try {
                TimeUnit.SECONDS.sleep(0);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            testSpinLock.myUnLock();
        },"B").start();
        AtomicInteger atomicInteger = new AtomicInteger();
        atomicInteger.getAndIncrement();
    }
    public void myLock(){
        System.out.println(Thread.currentThread().getName()+"->lock");
        while (!aft.compareAndSet(null,Thread.currentThread())){
        }
    }
    public void myUnLock(){
        System.out.println(Thread.currentThread().getName()+"->unlock");
        aft.compareAndSet(Thread.currentThread(), null);
    }
}
 
                    
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号