JUC并发编程自旋锁(二十一)

自定义一个锁

 

package com.xizi.lock;

import java.util.concurrent.atomic.AtomicReference;

public class SpinlockDemo {
//    int 0
//    Thread null
  AtomicReference 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);
        }

}

 测试

 

 

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();
    }
}

JUC并发编程自旋锁(二十一)_第1张图片

你可能感兴趣的:(JUC并发编程(Java))