当前位置:网站首页>线程同步的两个方法
线程同步的两个方法
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()方法释放锁,
边栏推荐
- 全国气象数据/降雨量分布数据/太阳辐射数据/NPP净初级生产力数据/植被覆盖度数据
- 3GPP信道模型路损基础知识
- JS variable plus
- 腾讯云数据库公有云市场稳居TOP 2!
- SQL injection HTTP header injection
- [736. LISP syntax parsing]
- 使用Thread类和Runnable接口实现多线程的区别
- Run the command once per second in Bash- Run command every second in Bash?
- Talk about the importance of making it clear
- 【愚公系列】2022年7月 Go教学课程 005-变量
猜你喜欢
A simple and beautiful regression table is produced in one line of code~
JS also exports Excel
Leetcode(46)——全排列
如何设计 API 接口,实现统一格式返回?
IMS data channel concept of 5g vonr+
[Android kotlin collaboration] use coroutinecontext to realize the retry logic after a network request fails
[736. LISP syntax parsing]
PMP证书有没有必要续期?
AttributeError: module ‘torch._ C‘ has no attribute ‘_ cuda_ setDevice‘
c语言神经网络基本代码大全及其含义
随机推荐
Flask project uses flask socketio exception: typeerror: function() argument 1 must be code, not str
vector和类拷贝构造函数
JS input and output
Can I specify a path in an attribute to map a property in my class to a child property in my JSON?
带你遨游银河系的 10 种分布式数据库
【PHP SPL笔记】
Using thread class and runnable interface to realize the difference between multithreading
Techniques d'utilisation de sublime
STM32F103ZE+SHT30检测环境温度与湿度(IIC模拟时序)
全国气象数据/降雨量分布数据/太阳辐射数据/NPP净初级生产力数据/植被覆盖度数据
If you‘re running pod install manually, make sure flutter pub get is executed first.
为什么很多人对技术债务产生误解
CentOS 7.9安装Oracle 21c历险记
App embedded H5 --- iPhone soft keyboard blocks input text
3GPP信道模型路损基础知识
《二》标签
Operand of null-aware operation ‘!‘ has type ‘SchedulerBinding‘ which excludes null.
How to design API interface and realize unified format return?
Markdown编辑器
LabVIEW在打开一个新的引用,提示内存已满