自旋锁的实现(CAS原理)

174 阅读1分钟

首先我们自己写上一把自旋锁,其中底层用的到CAS原理:

public class spinLockDemo {

    //int 0
    //Thread null
    AtomicReference<Thread> atomicReference = new AtomicReference<>();
    //加锁
    public void mylock(){
        Thread thread = Thread.currentThread();
        System.out.println(Thread.currentThread().getName()+"==> mylock");
        //自旋锁
        while(!atomicReference.compareAndSet(null,thread)){   //CAS实现原理
        }
    }
    //解锁
    public void myunlock(){
        Thread thread = Thread.currentThread();
        System.out.println(Thread.currentThread().getName() + "==> myunlock");
        atomicReference.compareAndSet(thread,null);
    }
}

然后我们自己创建我们的测试类:

spinLockDemo lock = new spinLockDemo();  //造一把锁
//启动两个线程,之间休眠一秒,为的是让t1线程先拿到锁
new Thread(()->{
    lock.mylock();
    try {
        TimeUnit.SECONDS.sleep(10);
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        lock.myunlock();
    }
},"t1").start();

try {
    TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
    e.printStackTrace();
}

new Thread(()->{
    lock.mylock();
    try {
        TimeUnit.SECONDS.sleep(3);
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        lock.myunlock();
    }
},"t2").start();

我们会发现只有当t1线程结束之后t2线程才会结束,这是因为t1在拿到锁以后,通过 while(!atomicReference.compareAndSet(null,thread))进行自旋,直到休眠十秒后 才可以释放这个锁,从而t2才可以拿到这个锁,程序才能执行下去