实现自己的自旋锁

public class MyLock {

    static AtomicReference<Thread> atomicReference = new AtomicReference<>();

     public static void myLock(){

         System.out.println(Thread.currentThread().getName() + "进来了");
         while (!atomicReference.compareAndSet(null,Thread.currentThread())){
             System.out.println(Thread.currentThread().getName() + "wait...");
         }
     }

     public static void myUnLock(){
         System.out.println(Thread.currentThread().getName() + "出去了");
         atomicReference.compareAndSet(Thread.currentThread(),null);
     }


    public static void main(String[] args) {
        new Thread(()->{
            myLock();
            try {
                TimeUnit.SECONDS.sleep(4);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName());
            myUnLock();
        },"a").start();

        new Thread(()->{
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            myLock();
            System.out.println(Thread.currentThread().getName());
            myUnLock();
        },"b").start();
    }
}

a进来了
b进来了
bwait...
bwait...
bwait...
a出去了
bwait...
b
b出去了

上一篇:NPOI的WORD填表


下一篇:室友竟只在2021的最后一天就学会了哈希表