自旋锁代码实现

    xiaoxiao2022-07-12  156

    package com.xiang.lock; import java.sql.Time; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; public class SpinLockDemo { AtomicReference<Thread> atomicReference = new AtomicReference<>(); public void mylock(){ Thread thread = Thread.currentThread(); System.out.println(thread.getName() + "进来获取锁了"); while (!atomicReference.compareAndSet(null,thread)){ } } public void unlock(){ Thread thread = Thread.currentThread(); atomicReference.compareAndSet(thread,null); System.out.println(thread.getName()+ " 释放锁"); } public static void main(String[] args) { SpinLockDemo spinLockDemo = new SpinLockDemo(); new Thread(()->{ spinLockDemo.mylock(); try { TimeUnit.SECONDS.sleep(10); }catch (InterruptedException e){ e.printStackTrace(); } spinLockDemo.unlock(); },"t1").start(); try { TimeUnit.SECONDS.sleep(1); }catch (InterruptedException e){ e.printStackTrace(); } new Thread(()->{ spinLockDemo.mylock(); spinLockDemo.unlock(); },"t2").start(); } }
    最新回复(0)