实现自旋锁

package com.example.demo.test;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

public class Test1 {

    AtomicReference atomicReference = new AtomicReference<>();
    public void lock(){
        Thread thread = Thread.currentThread();
        System.out.println(thread.getName() + "锁起来111");
        while (atomicReference.compareAndSet(null,thread)){

        }
        System.out.println(thread.getName() + "锁起来222");
    }

    public void unLock(){
        Thread thread = Thread.currentThread();
        System.out.println(thread.getName() + "解锁111");
        atomicReference.compareAndSet(thread,null);
        System.out.println(thread.getName() + "解锁222");
    }

    public static void main(String[] args) throws Exception{

        Test1 test1 = new Test1();
        new Thread(()->{
            test1.lock();
            test1.unLock();
        },"AA").start();
        TimeUnit.SECONDS.sleep(1);
        new Thread(()->{
            test1.lock();
        },"BB").start();
    }
}

你可能感兴趣的:(java基础)