class SpinLockdemo{
AtomicReference<Thread> atomicReference = new AtomicReference<>();
public SpinLockdemo(){
}
public void myLock(){
Thread thread = Thread.currentThread();
System.out.println(thread.getName()+"进入");
while(!atomicReference.compareAndSet(null, thread))
{
}
}
public void unlock(){
Thread thread = Thread.currentThread();
System.out.println(thread.getName()+"出来");
atomicReference.compareAndSet(thread, null);
}
}
public static void main(String args[])
{
/*
* 自旋锁实现
* */
final SpinLockdemo test = new SpinLockdemo();
new Thread(new Runnable(){
public void run(){
test.myLock();
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
test.unlock();
}
},"A").start();;
try {
TimeUnit.SECONDS.sleep(1); //停1s,保证A在B之前执行
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
new Thread(new Runnable(){
public void run(){
test.myLock();
test.unlock();
}
},"B").start();
}