当前位置:网站首页>《利用CAS实现自旋锁》
《利用CAS实现自旋锁》
2022-06-23 15:25:00 【weixin_43766298】
1.自旋锁概念
- 自旋锁(spinlock):是指当一个线程在获取锁的时候,如果锁已经被其它线程获取,那么该线程将循环等待,然后不断的判断锁是否能够被成功获取,直到获取到锁才会退出循环。
2.编写自旋锁
import java.util.concurrent.atomic.AtomicBoolean;
//自旋锁
public class SpinLock {
//CAS
private AtomicBoolean cas = new AtomicBoolean(false);
//锁持有者线程
private Thread spinLockOwnerThread = null;
public void lock(){
while (!cas.compareAndSet(false,true))
{
//CAS自旋
}
spinLockOwnerThread = Thread.currentThread();
}
public void unLock(){
//当前线程等于锁持有着线程才允许解锁
if (Thread.currentThread()==spinLockOwnerThread)
{
spinLockOwnerThread = null;
cas.set(false);
//最后设置CAS的值为false,为什么?
//如果先执行cas.set(false),此时又来了一个新的线程,
//成功过了CAS的compareAndSet,
//将 spinLockOwnerThread 指向Thread.currentThread();
//最后再执行spinLockOwnerThread = null;
//这会导致最后持有锁的线程无法解锁
//也就是无法通过Thread.currentThread()==spinLockOwnerThread判断
//从而导致程序一直阻塞
}
}
}
3.测试自旋锁
class Test {
//引入自旋锁
private static final SpinLock spinLock = new SpinLock();
public static void main(String[] args) {
Thread t1 = new Thread(Test::run,"t1");
Thread t2 = new Thread(Test::run,"t2");
Thread t3 = new Thread(Test::run,"t3");
Thread t4 = new Thread(Test::run,"t4");
t1.start();
t2.start();
t3.start();
t4.start();
}
public static void run(){
spinLock.lock();
System.out.println(Thread.currentThread().getName());
try
{
Thread.sleep(5000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
finally
{
spinLock.unLock();
}
}
}
边栏推荐
- Analysis of graphical level-1 programming problem of Electronic Society: cat and mouse
- Thymeleaf——学习笔记
- Android kotlin collaboration Async
- Sfod: passive domain adaptation and upgrade optimization, making the detection model easier to adapt to new data (attached with paper Download)
- JS garbage collection
- MySQL日志管理怎么配置
- Introduction to the push function in JS
- 嵌入式软件架构设计-程序分层
- CAS操作在ARM和x86下的不同实现
- 现在我要买股票,怎么开户?手机开户安全么?
猜你喜欢

Six programming insights in these five years!

Important knowledge of golang: sync Once explanation

JS garbage collection

golang 重要知识:sync.Once 讲解

Volatile~ variables are not visible under multithreading

FPN特征金字塔网络
![[普通物理] 半波损失 等厚与等倾干涉](/img/66/e0acce623092ecd38e59e38867521d.png)
[普通物理] 半波损失 等厚与等倾干涉

Jsr303 data verification

Important knowledge of golang: mutex

Important knowledge of golang: sync Cond mechanism
随机推荐
Sfod: passive domain adaptation and upgrade optimization, making the detection model easier to adapt to new data (attached with paper Download)
spdlog记录日志示例 - 使用sink创建logger
Memory Consistency and Cache Coherence —— 内存一致性
列表查询排序参数处理
创建好后的模型,对Con2d, ConvTranspose2d ,以及归一化BatchNorm2d函数中的变量进行初始化
513. Find Bottom Left Tree Value
苹果 iPhone、三星手机等电子产品开始经平行进口渠道进入俄罗斯
The work and development steps that must be done in the early stage of the development of the source code of the live broadcasting room
PHP 2D array insert
The "shoulder" of sales and service in the heavy truck industry, Linyi Guangshun deep ploughing product life cycle service
重卡界销售和服务的“扛把子”,临沂广顺深耕产品全生命周期服务
Important knowledge of golang: atomic atomic operation
Do you understand Mipi c-phy protocol? One of the high-speed interfaces for mobile phones
Explore the "store" on the cloud. The cloud store is newly upgraded!
139. Séparation des mots
Convert JSON file of labelme to coco dataset format
HBuilderX-Light 主题能不能加个批注功能?
JS里的数组
Analysis of graphical level-1 programming problem of Electronic Society: cat and mouse
Usestate vs useref and usereducer: similarities, differences and use cases