自旋锁

import java.util.concurrent.atomic.AtomicReference;

/**
 * @Author: wz
 * @Date: 2022/7/12 23:51
 * 自旋锁
 */
public class SpinlockDemo {

    // int 0 Thread null
    AtomicReference atomicReference = new AtomicReference<>();

    // 加锁
    public void myLock(){
        Thread thread =  Thread.currentThread();
        System.out.println(Thread.currentThread().getName()+"--> mylock");
        // 自旋锁
        while (!atomicReference.compareAndSet(null, thread)){

        }
    }

    // 解锁
    public void myUnLock(){
        Thread thread =  Thread.currentThread();
        System.out.println(Thread.currentThread().getName()+"--> myUnlock");
        atomicReference.compareAndSet(thread, null);
    }
}

/**
 * @Author: wz
 * @Date: 2022/7/13 0:00
 */
public class TestSpinLock {
    public static void main(String[] args) throws InterruptedException {
        SpinlockDemo lock = new SpinlockDemo();


        new Thread(() -> {
            lock.myLock();
            try {
                Thread.sleep(4000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.myUnLock();
            }
        }, "A").start();

        Thread.sleep(1000);
        new Thread(() -> {

            lock.myLock();
            try {
                Thread.sleep(4000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.myUnLock();
            }
        }, "B").start();

    }
}

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