實現自旋鎖

package com.example.demo.test;

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

public class Test1 {

    AtomicReference<Thread> 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();
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章