概念:
- 是指嘗試獲取鎖的線程不會(huì)立即阻塞,而是采用循環(huán)的方式嘗試獲取鎖崇渗。
優(yōu)點(diǎn):減少線程上下文切換的消耗字逗。
缺點(diǎn):循環(huán)會(huì)消耗CPU京郑。
代碼驗(yàn)證:
package com.yy.java;
/**
* @author yuanyong:
* @version 2021年2月26日 下午4:04:22
* 類說(shuō)明 驗(yàn)證自旋鎖
*/
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
public class TestSpinLock {
AtomicReference<Thread> atomicReference = new AtomicReference<>();
public void mylock() {
Thread thread = Thread.currentThread();
System.out.println(thread.getName()+"-->mylock");
while (!atomicReference.compareAndSet(null, thread)) {
System.out.println(thread.getName()+"-->trying get lock!");
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void myUnlock() {
Thread thread = Thread.currentThread();
atomicReference.compareAndSet(thread, null);
System.out.println(thread.getName()+"-->myUnlock");
}
public static void main(String[] args) {
TestSpinLock testSpinLock = new TestSpinLock();
new Thread(() -> {
testSpinLock.mylock();
try {
TimeUnit.SECONDS.sleep(5); //T1占用5s
} catch (Exception e) {
e.printStackTrace();
}
testSpinLock.myUnlock();
},"T1").start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (Exception e) {
e.printStackTrace();
}
new Thread(() -> {
testSpinLock.mylock();
try {
TimeUnit.SECONDS.sleep(1);
} catch (Exception e) {
e.printStackTrace();
}
testSpinLock.myUnlock();
},"T2").start();
}
}
*****************************執(zhí)行結(jié)果:**********************************
T1-->mylock
T2-->mylock
T2-->trying get lock葫掉!
T2-->trying get lock些举!
T2-->trying get lock!
T2-->trying get lock挖息!
T1-->myUnlock
T2-->myUnlock
分析:根據(jù)結(jié)果效果可以發(fā)現(xiàn)金拒,在T1線程占用鎖的5s期間兽肤,T2線程每隔1s就嘗試獲取一次鎖套腹。