当前位置:网站首页>线程同步的两个方法
线程同步的两个方法
2022-07-06 23:09:00 【洋啊桑815】
1:同步代码块
public void UpdateMoney(Double price){
System.out.println(Thread.currentThread() + "进来了");
synchronized (this){
if(price<=money){
//取钱
System.out.println(Thread.currentThread()+"来取钱"+price);
money-=price;
System.out.println("剩余余额"+money);
}else {
System.out.println(Thread.currentThread()+"抱歉!余额不足");
}
}
} synchronized (同步锁对象){
操作共享资源的代码
}
注意一点:同步锁对象要保持唯一性,在对实例方法使用时,建议使用共享的资源,比如this,
在对静态方法使用时,建议使用字节码,比如:类名.class
方法2:同步方法
/***
* 取钱的方法
* @param price 要取的金额
*/
public synchronized void UpdateMoney(Double price){
System.out.println(Thread.currentThread() + "进来了");
Lock lock=new ReentrantLock();
lock.lock();
if(price<=money){
//取钱
System.out.println(Thread.currentThread()+"来取钱"+price);
money-=price;
System.out.println("剩余余额"+money);
}else {
System.out.println(Thread.currentThread()+"抱歉!余额不足");
}
lock.unlock();
}修饰符 后面 加上synchronized,然后调用Lock接口的ReentrantLock实现类,
使用 lock()方法上锁,unlock()方法释放锁,
边栏推荐
- STM32F103ZE+SHT30检测环境温度与湿度(IIC模拟时序)
- 谈谈讲清楚这件事的重要性
- 01 machine learning related regulations
- Test interview | how much can you answer the real test interview question of an Internet company?
- c语言神经网络基本代码大全及其含义
- The sooner you understand the four rules of life, the more blessed you will be
- Sublime tips
- offer如何选择该考虑哪些因素
- JDBC link Oracle reference code
- No experts! Growth secrets for junior and intermediate programmers and "quasi programmers" who are still practicing in Universities
猜你喜欢

AttributeError: module ‘torch._C‘ has no attribute ‘_cuda_setDevice‘

Ansible概述和模块解释(你刚走过了今天,而扑面而来的却是昨天)

Weebly mobile website editor mobile browsing New Era

一个酷酷的“幽灵”控制台工具

U++ metadata specifier learning notes

HarmonyOS第四次培训
![[Android kotlin collaboration] use coroutinecontext to realize the retry logic after a network request fails](/img/e0/04f06d464e77012fbfc919e07cbb66.png)
[Android kotlin collaboration] use coroutinecontext to realize the retry logic after a network request fails

JS also exports Excel

装饰器基础学习02

Why do many people misunderstand technical debt
随机推荐
QT控件样式系列(一)之QSlider
Batch normalization (Standardization) processing
STM32F103实现IAP在线升级应用程序
指针与数组在函数中输入实现逆序输出
想要选择一些部门优先使用 OKR, 应该如何选择试点部门?
Analysis -- MySQL statement execution process & MySQL architecture
最全常用高数公式
National meteorological data / rainfall distribution data / solar radiation data /npp net primary productivity data / vegetation coverage data
When knative meets webassembly
5G VoNR+之IMS Data Channel概念
腾讯云数据库公有云市场稳居TOP 2!
A simple and beautiful regression table is produced in one line of code~
How to design API interface and realize unified format return?
Why do many people misunderstand technical debt
Dynamically generate tables
Common Oracle SQL statements
【二叉树】二叉树寻路
Tree map: tree view - draw covid-19 array diagram
Weebly mobile website editor mobile browsing New Era
How to choose an offer and what factors should be considered