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