Java中利用AtomicReference手写自旋锁Demo

自旋锁简介

自旋锁是一种非阻塞锁,抢到执行权的线程并不会自旋,自旋的精髓在于没抢到执行权的线程,它们会空转cpu,一直循环,这就是自旋,并非把线程改为阻塞状态.它们还是在运行的,自旋重试想获取锁.

源代码

public class SpinLockDemo {
     

    public static AtomicReference<Thread>  spinLock = new AtomicReference<>();
    private static Integer count = 0;

    public static void main(String[] args) {
     
        new Thread(()->{
     
            myLock();
            for (int i = 0; i < 100; i++) {
     
                count ++;
            }
            unLock();
        },"t1").start();

        new Thread(()->{
     
            myLock();
            for (int i = 0; i < 100; i++) {
     
                count ++;
            }
            unLock();
        },"t2").start();

        while (Thread.activeCount()>2){
      }
        System.out.println(count);
    }

    public static void myLock(){
     
        Thread thread = Thread.currentThread();
        while (!spinLock.compareAndSet(null,thread)){
     
//            System.out.println(thread.getName()+"自旋中=================");
        }

        System.out.println(Thread.currentThread().getName()+"获取到了锁");

    }

    public static void unLock(){
     
        Thread thread = Thread.currentThread();
        spinLock.compareAndSet(thread,null);
        System.out.println(Thread.currentThread().getName()+"释放了锁");
    }
}

输出结果

这段代码是两个线程,每个线程for循环100次,执行count++,count默认等于0
执行了5次,count都是200,说明这个自旋锁是成功的,能保证原子性,不会跳号重号.
Java中利用AtomicReference手写自旋锁Demo_第1张图片

你可能感兴趣的:(Java,多线程,JUC,java,多线程,并发编程,thread)