自旋锁CAS例子

`

package spin;

import java.util.concurrent.atomic.AtomicReference;

public class spinDemo {

    AtomicReference atomicReference = new AtomicReference<>();

    //加锁

    public void myLock(){

        Thread thread = Thread.currentThread();

        //重点 使用CAS

        while (!atomicReference.compareAndSet(null, thread)){

          System.out.println(Thread.currentThread().getName()+"\t想拿到锁");

        }

        System.out.println(Thread.currentThread().getName()+"\t拿到锁");

    }

    //解锁

    public void myUnLock(){

        Thread thread = Thread.currentThread();

        System.out.println(Thread.currentThread().getName()+"\t解锁");

        atomicReference.compareAndSet(thread, null);

    }

}

`

你可能感兴趣的:(自旋锁CAS例子)