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(); } }
实现自旋锁
最新推荐文章于 2024-04-17 22:04:36 发布