自旋锁的好处:循环比较获取没有类似wait的阻塞
package SpinLockDemo;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
public class SipinLockDemo {
AtomicReference<Thread> atomicReference = new AtomicReference<>();
public void lock(){
Thread thread = Thread.currentThread();
System.out.println(Thread.currentThread().getName()+"\t"+"----come in");
while (!atomicReference.compareAndSet(null,thread)){
}
}
public void unlock(){
Thread thread = Thread.currentThread();
atomicReference.compareAndSet(thread,null);
System.out.println(Thread.currentThread().getName()+"\t"+"task over,unLock...");
}
public static void main(String[] args) throws InterruptedException {
SipinLockDemo sipinLockDemo = new SipinLockDemo();
new Thread(() -> {
sipinLockDemo.lock();
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
sipinLockDemo.unlock();
}, "A").start();
TimeUnit.SECONDS.sleep(5);
new Thread(()->{
sipinLockDemo.lock();
sipinLockDemo.unlock();
},"B").start();
}
}
运行结果: