自己实现自旋锁

import java.util.concurrent.atomic.AtomicReference;

public class T7 {

    AtomicReference atomicReference = new AtomicReference<>();

    public void myLock(){
        Thread thread = Thread.currentThread();
        System.out.println(Thread.currentThread().getName() + " lock");

        while (!atomicReference.compareAndSet(null,thread)){

        }
    }

    public void unLock(){
        Thread thread = Thread.currentThread();
        atomicReference.compareAndSet(thread,null);

        System.out.println(Thread.currentThread().getName() + " unlock");
    }

    public static void main(String[] args) {

       T7 t7 = new T7();

       new Thread(new Runnable() {
           @Override
           public void run() {
               t7.myLock();
               try {
                   Thread.sleep(5000);
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
               t7.unLock();
           }
       },"a").start();

       new Thread(new Runnable() {
           @Override
           public void run() {
               t7.myLock();
               try {
                   Thread.sleep(1000);
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
               t7.unLock();
           }
       },"b").start();
    }
}

运行结果:
自己实现自旋锁_第1张图片

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