package juc.spinlock;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
public class TestSpinLock {
public static void main(String[] args) {
TestSpinLock testSpinLock = new TestSpinLock();
new Thread(()->{
testSpinLock.lock();
try { TimeUnit.SECONDS.sleep( 5 ); } catch (InterruptedException e) { e.printStackTrace(); }
testSpinLock.unlock();
},"A").start();
new Thread(()->{
testSpinLock.lock();
try { TimeUnit.SECONDS.sleep( 5 ); } catch (InterruptedException e) { e.printStackTrace(); }
testSpinLock.unlock();
},"B").start();
}
AtomicReference<Thread> atomicReference = new AtomicReference<>();
public void lock() {
Thread thread = Thread.currentThread();
System.out.println(thread.getName()+" come in lock");
while(!atomicReference.compareAndSet(null,thread)){
}
System.out.println(thread.getName()+" leave lock");
}
public void unlock(){
Thread thread = Thread.currentThread();
System.out.println(thread.getName()+" come in unlock");
while(!atomicReference.compareAndSet(thread,null)){
}
System.out.println(thread.getName()+" leave unlock");
}
}
JUC-spinLock
最新推荐文章于 2024-11-13 22:59:02 发布