Skip to content

百题通关(下)[废弃]

手撕自旋锁CAS

用AtomicReference, 传入Thread

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

/**
 * @author York
 * @className SpinLockDemo
 * @date 2024/09/14 22:00
 * @description 手撕CAS 利用AtomicReference原子引用
 */
public class SpinLockDemo {

    AtomicReference<Thread> bookAtomicReference = new AtomicReference<>();

    public void lock(){
        Thread thread = Thread.currentThread();
        System.out.println(thread.getName() + "------come in...");
        while (!bookAtomicReference.compareAndSet(null, thread)) {
        }
    }

    public void unlock(){
        Thread thread = Thread.currentThread();
        bookAtomicReference.compareAndSet(thread,null);
        System.out.println(thread.getName() + "------come out...");
    }

    public static void main(String[] args) {
        SpinLockDemo spinLockDemo = new SpinLockDemo();
        new Thread(() -> {
            spinLockDemo.lock();
            try {TimeUnit.SECONDS.sleep(2);} catch (InterruptedException e){ e.printStackTrace();}
            spinLockDemo.unlock();
        }).start();
        // 为了让上面那个线程先持有锁, 让下面的锁争用
        try {TimeUnit.MILLISECONDS.sleep(500);} catch (InterruptedException e){ e.printStackTrace();}

        new Thread(() -> {
            spinLockDemo.lock();
            System.out.println(Thread.currentThread().getName() + " says:------I got it...");
            spinLockDemo.unlock();
        }).start();
    }
}

技术漫游

本站访客数 人次 本站总访问量