一个简单的自旋锁

package spin;

import java.util.concurrent.atomic.AtomicReference;

public class spinDemo {
    AtomicReference atomicReference = new AtomicReference<>();
    //加锁
    public void myLock(){
        Thread thread = Thread.currentThread(); 
        //重点 使用CAS
        while (!atomicReference.compareAndSet(null, thread)){
           System.out.println(Thread.currentThread().getName()+"\t想拿到锁");
        }
         System.out.println(Thread.currentThread().getName()+"\t拿到锁");
    }
    //解锁
    public void myUnLock(){
        Thread thread = Thread.currentThread();
        System.out.println(Thread.currentThread().getName()+"\t解锁");
        atomicReference.compareAndSet(thread, null);
    }
}

测试类

package spin;

import java.util.concurrent.TimeUnit;

public class Test {
    public static void main(String[] args) {
        spinDemo lock = new spinDemo();

        new Thread(()->{

            lock.myLock();
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.myUnLock();
            }
        },"A").start();


        new Thread(()->{

            lock.myLock();
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.myUnLock();
            }
        },"B").start();
    }
}

执行结果如下:
一个简单的自旋锁_第1张图片
一个简单的自旋锁_第2张图片

你可能感兴趣的:(Java)