package Juc;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
/**
* 自旋锁的手动实现
* 原理对当前线程进行CAS比较交换操作,当第一个线程进入后,期待值为null,
* 更新值为当前线程,第二个线程进入由于期待值(null)与主存有值违背,
* 进行自旋循环等待
*
*
*
*/
public class SpinLock {
AtomicReference<Thread> atomicReference = new AtomicReference<>();
public void ownLock(){
Thread thread = Thread.currentThread();
System.out.println(Thread.currentThread().getName()+"\t come in");
while(!atomicReference.compareAndSet(null, thread)){
}
}
public void Unownlock(){
Thread thread = Thread.currentThread();
atomicReference.compareAndSet(thread, null);
System.out.println(Thread.currentThread().getName()+"\t invoked myunlock!");
}
public static void main(String[] args) {
SpinLock spinLock= new SpinLock();
new Thread(() ->
{
spinLock.ownLock();
try{TimeUnit.SECONDS.sleep(5);}catch (Exception e){e.printStackTrace();}
spinLock.Unownlock();
},"AA").start();
try{TimeUnit.SECONDS.sleep(1);}catch (Exception e){e.printStackTrace();}
new Thread(() ->
{
spinLock.ownLock();
try{TimeUnit.SECONDS.sleep(1);}catch (Exception e){e.printStackTrace();}
spinLock.Unownlock();
},"BB").start();
}
}
自旋锁的实现
最新推荐文章于 2022-03-07 14:43:14 发布