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
阅读 949 · 发布于 2021-04-06
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb扫描下方二维码关注公众号和小程序↓↓↓

昵称:
随便看看
换一批
-
OpenResty 常用 HTTP 请求 API阅读 3689
-
SQL 查询出成绩表中成绩大于 90 的学生名字阅读 722
-
Java 并发编程之 CyclicBarrier阅读 1238
-
MySQL 内置函数之时间函数阅读 1297
-
软考-系统架构设计师:物联网 IoT阅读 949
-
走进 Rust:Drop trait阅读 1170
-
IntelliJ IDEA 选择 Open matching files in associated application后更改打开方式阅读 3891
-
Android Gradle 去除重复依赖阅读 2562
-
Charles 提示 SSL Proxying not enabled for this host阅读 7562
-
Golang 命令之 godoc阅读 667