自旋鎖,是指不會阻塞當前線程,而是採用循環的方式去獲取鎖,這樣的話減少上下文切換,但是同時會消耗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");
}
核心原理爲利用原子更新引用。