JUC Concurrent Programming Spinlock (21)

Customize a lock

 

package com.xizi.lock;

import java.util.concurrent.atomic.AtomicReference;

public class SpinlockDemo {
//    int 0
//    Thread null
  AtomicReference<Thread> 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()+"===>MyUBLock");
        atomicReference.compareAndSet(thread,null);
        }

}

 test

 

 

package com.xizi.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

public class TestSpinLock {
    public static void main(String[] args) {
//        ReentrantLock reentrantLock = new ReentrantLock();
//        reentrantLock.lock();
//        reentrantLock.unlock();
        //底层使用的自旋锁CAS
        SpinlockDemo lock = new SpinlockDemo();
        new Thread(()->{
            lock.MyLock();

            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

          finally {
                lock.MyUnLock();
            }
        },"T1").start();
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(()->{
            lock.MyLock();

            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                lock.MyUnLock();
            }
        },"T2").start();
    }
}

Guess you like

Origin blog.csdn.net/weixin_45480785/article/details/105390825