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");
}
}
04-25
03-21
02-25
07-05
04-29
04-29
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交