如何利用AtomicReference写一个简单的自旋锁?

1. 自旋锁成品代码如下:


package lock.spinlock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author wuyiccc
 * @date 2020/7/19 10:37
 * 岂曰无衣,与子同袍~
 */
public class SpinLock {

    private AtomicReference sign = new AtomicReference<>();


    public void lock() {
        Thread current = Thread.currentThread();

        while (!sign.compareAndSet(null, current)) {
            System.out.println("获取自旋锁失败,再次尝试");
        }
    }

    public void unlock() {
        Thread current = Thread.currentThread();
        sign.compareAndSet(current, null);
    }

    public static void main(String[] args) {

        SpinLock lock = new SpinLock();

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + "开始尝试获取自旋锁...");
                lock.lock();
                System.out.println(Thread.currentThread().getName() + "获取自旋锁成功...");
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    System.out.println(Thread.currentThread().getName() + "释放了自旋锁...");
                    lock.unlock();
                }
            }
        };
        Thread t1 = new Thread(runnable, "线程1");
        Thread t2 = new Thread(runnable, "线程2");
        t1.start();
        t2.start();
    }


}

2. 核心代码讲解

image.png

你可能感兴趣的:(java,并发编程,锁)