概念:
- 是指尝试获取锁的线程不会立即阻塞,而是采用循环的方式尝试获取锁。
优点:减少线程上下文切换的消耗。
缺点:循环会消耗CPU。
代码验证:
package com.yy.java;
/**
* @author yuanyong:
* @version 2021年2月26日 下午4:04:22
* 类说明 验证自旋锁
*/
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();
}
}
*****************************执行结果:**********************************
T1-->mylock
T2-->mylock
T2-->trying get lock!
T2-->trying get lock!
T2-->trying get lock!
T2-->trying get lock!
T1-->myUnlock
T2-->myUnlock
分析:根据结果效果可以发现,在T1线程占用锁的5s期间,T2线程每隔1s就尝试获取一次锁。
网友评论