自旋锁,是指不会阻塞当前线程,而是采用循环的方式去获取锁,这样的话减少上下文切换,但是同时会消耗CPU资源。
//---------------------------自旋锁-----------------------
private static AtomicReference<Thread> atomicReference=new AtomicReference<>(null);
public void lock(){
//自旋
while(!atomicReference.compareAndSet(null,Thread.currentThread())){
}
}
public void unluck(){
//自旋
while(!atomicReference.compareAndSet(Thread.currentThread(),null)){
}
}
@Test
public void test07() throws InterruptedException {
Thread thread01=new Thread(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+":尝试获取锁");
lock();
System.out.println(Thread.currentThread().getName()+":获取到锁");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+":开始释放锁");
unluck();
System.out.println(Thread.currentThread().getName()+":释放锁完成");
}
});
thread01.setName("T1");
thread01.start();
Thread.sleep(1000);
Thread thread02=new Thread(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+":尝试获取锁");
lock();
System.out.println(Thread.currentThread().getName()+":获取到锁");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+":开始释放锁");
unluck();
System.out.println(Thread.currentThread().getName()+":释放锁完成");
}
});
thread02.setName("T2");
thread02.start();
while (Thread.activeCount()>2){}
System.out.println("run over");
}
核心原理为利用原子更新引用。