Java 中的自旋锁
Java juc 锁 About 1,730 words自旋锁
使用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
Views: 2,388 · Posted: 2021-04-06
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb/LiteNote扫描下方二维码关注公众号和小程序↓↓↓
Loading...