自旋锁

自旋锁

  • A线程进来没问题,不解锁的情况下,B线程进来会空循环等待A解锁
package Lock.SpinlockDemo;

import java.util.concurrent.atomic.AtomicReference;

public class SpinlockA {
    // int 0
    //thread  null
    AtomicReference<Thread> atomicReference = new AtomicReference<>();

    //加锁
    public void lock() {
        Thread thread = Thread.currentThread();
        //自旋锁
        // compareAndSet() 如果符合条件,就会set值。
        // 返回true set成功
        // 返回false 没set
        boolean setSuccessful = atomicReference.compareAndSet(null, thread);
        while (!setSuccessful) {
            //第二个线程进来,setSuccessful为false,一直空循环
        }
        System.out.println(Thread.currentThread().getName() + "-->myLock");
    }

    //解锁
    public void unlock() {
        Thread thread = Thread.currentThread();
        System.out.println(Thread.currentThread().getName() + "-->myUnLock");

        atomicReference.compareAndSet(thread, null);
    }
}
package Lock.SpinlockDemo;

import java.util.concurrent.TimeUnit;

public class Test {
    public static void main(String[] args) throws InterruptedException {
        SpinlockA spinlockA = new SpinlockA();

        new Thread(() -> {
            spinlockA.lock();
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                spinlockA.unlock();
            }
        }, "A").start();

        TimeUnit.SECONDS.sleep(1);
        new Thread(() -> {
            spinlockA.lock();
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                spinlockA.unlock();
            }
        }, "B").start();
    }
}
posted @   小幼虫虫  阅读(30)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示