用CAS思想实现一个自旋锁

public class SpinLockDemo {
    //原子引用线程
    AtomicReference<Thread> atomicReference = new AtomicReference<>();

    public void myLock() {
        Thread thread = Thread.currentThread();
        System.out.println(thread.getName() + "\t invoke myLock()");
//模拟自旋 while (!atomicReference.compareAndSet(null, thread)) { } } public void myUnlock() { Thread thread = Thread.currentThread(); System.out.println(thread.getName() + "\t invoke myUnlock()"); atomicReference.compareAndSet(thread, null); } public static void main(String[] args) throws InterruptedException { SpinLockDemo spinLockDemo = new SpinLockDemo(); new Thread(() -> { spinLockDemo.myLock(); try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); } spinLockDemo.myUnlock(); }, "t1").start(); TimeUnit.SECONDS.sleep(1); new Thread(() -> { spinLockDemo.myLock(); try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } spinLockDemo.myUnlock(); }, "t2").start(); } }

  

posted @ 2024-12-08 20:46  达摩克利斯之剑  阅读(13)  评论(0)    收藏  举报