Java 中的自旋锁
Java juc 锁 大约 1730 字自旋锁
使用CAS
+无限循环组成自旋锁。
原子引用类保存持有锁的线程,其他线程将使用CAS
+自旋争夺锁。
示例代码
public class SpinLockDemo {
AtomicReference<Thread> atomicReference = new AtomicReference<>();
public void myLock () {
Thread thread = Thread.currentThread();
System.out.println(LocalDateTime.now() +"\t" + thread.getName() + "\t come in");
while (!atomicReference.compareAndSet(null, thread)) {
System.out.println(thread.getName() + "自旋中");
}
}
public void myUnLock() {
Thread thread = Thread.currentThread();
atomicReference.compareAndSet(thread, null);
System.out.println(LocalDateTime.now() +"\t" + thread.getName() + "\t invoke my unlock");
}
public static void main(String[] args) {
SpinLockDemo spinLockDemo = new SpinLockDemo();
new Thread(() -> {
spinLockDemo.myLock();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
spinLockDemo.myUnLock();
},"AAA").start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(() -> {
spinLockDemo.myLock();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
spinLockDemo.myUnLock();
}, "BBB").start();
}
}
输出:
2021-03-28T18:50:49.923 AAA come in
2021-03-28T18:50:50.870 BBB come in
BBB自旋中
BBB自旋中
BBB自旋中
2021-03-28T18:50:50.937 AAA invoke my unlock
2021-03-28T18:50:51.938 BBB invoke my unlock
阅读 1517 · 发布于 2021-04-06
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb扫描下方二维码关注公众号和小程序↓↓↓

昵称:
随便看看
换一批
-
filebeat read: connection reset by peer阅读 3440
-
Redis 命令行显示中文阅读 3192
-
Hyper-V Default Switch 无法联网解决办法阅读 3737
-
Spring 与 JPA 中的 @Transactional 注解的区别阅读 190
-
Android 不允许用户清理数据阅读 1876
-
Kubernetes 数据存储 Secret阅读 1016
-
微信小程序基于 Parser 添加长按复制、代码高亮等功能阅读 4257
-
Docker 部署 Jenkins阅读 1103
-
Android 根据包名启动 Activity阅读 2989
-
设计模式之代理模式阅读 1374