java 实现自旋锁_java自旋锁的代码实现
自旋鎖:spinlock
是指嘗試獲取鎖的線程不會立即阻塞,而是采用循環的方式獲取鎖,這樣的好處是減少線程上下文切換的消耗,缺點是循環好用CPU
代碼:
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
public class SpinLockDemo {
//原子引用線程
AtomicReference atomicReference = new AtomicReference<>();
public void myLock() {
Thread thread = Thread.currentThread();
System.out.println(Thread.currentThread().getName() + "\t come in ");
while (!atomicReference.compareAndSet(null, thread)) {
}
}
public void myUnlock() {
Thread thread = Thread.currentThread();
atomicReference.compareAndSet(thread, null);
System.out.println(Thread.currentThread().getName() + "\t invoked myUnlock()");
}
public static void main(String[] args) {
SpinLockDemo spinLockDemo = new SpinLockDemo();
new Thread(() -> {
spinLockDemo.myLock();
try {
TimeUnit.SECONDS.sleep(5);
}catch (InterruptedException e){
e.printStackTrace();
}
spinLockDemo.myUnlock();
}, "AA").start();
try {
TimeUnit.SECONDS.sleep(1);
}catch (InterruptedException e){
e.printStackTrace();
}
new Thread(() -> {
spinLockDemo.myLock();
try {
TimeUnit.SECONDS.sleep(1);
}catch (InterruptedException e){
e.printStackTrace();
}
spinLockDemo.myUnlock();
}, "BB").start();
}
}
原文:https://www.cnblogs.com/sunliyuan/p/12436777.html
總結
以上是生活随笔為你收集整理的java 实现自旋锁_java自旋锁的代码实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 联想拯救者r720适合java么_联想拯
- 下一篇: java反向注入_java 控制反转和依