复制代码
package com.mydemo;

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

import static java.lang.Thread.currentThread;

public class SpinLockDemo {

    AtomicReference<Thread> atomicReference=new AtomicReference<>();



    public void myLock(){
        Thread thread =  Thread.currentThread();
        System.out.println(currentThread().getName()+"\t come in!");

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

        }



    }

    public void myUnlock(){

        Thread thread = Thread.currentThread();
        atomicReference.compareAndSet(thread,null);
        System.out.println(currentThread().getName()+"\t invoke myUnlock!");
    }
    public static void main(String[] args) {
        SpinLockDemo spinLockDemo = new SpinLockDemo();
        new Thread(()->{
            spinLockDemo.myLock();
            try {
                            TimeUnit.SECONDS.sleep(5);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
            spinLockDemo.myUnlock();


        },"t1").start();
        try {
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

        // 1秒后,启动t2线程,开始占用这个锁
        new Thread(() -> {

            // 开始占有锁
            spinLockDemo.myLock();
            // 开始释放锁
            spinLockDemo.myUnlock();

        }, "t2").start();


    }
}
复制代码

 

posted on   upupup-999  阅读(48)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~



点击右上角即可分享
微信分享提示