当前位置:网站首页>线程同步的两个方法
线程同步的两个方法
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()方法释放锁,
边栏推荐
猜你喜欢
sublime使用技巧
Dynamically generate tables
记录一次压测经验总结
C语言中函数指针与指针函数
qt 简单布局 盒子模型 加弹簧
Error: No named parameter with the name ‘foregroundColor‘
A row of code r shows the table of Cox regression model
Common Oracle SQL statements
Monitoring cannot be started after Oracle modifies the computer name
c语言神经网络基本代码大全及其含义
随机推荐
When knative meets webassembly
《五》表格
How to package the parsed Excel data into objects and write this object set into the database?
The execution order of return in JS' try catch finally
Talk about the importance of making it clear
精彩速递|腾讯云数据库6月刊
np.random.shuffle与np.swapaxis或transpose一起时要慎用
Monitoring cannot be started after Oracle modifies the computer name
JS also exports Excel
2. Overview of securities investment funds
R descriptive statistics and hypothesis testing
指针与数组在函数中输入实现逆序输出
如何设计 API 接口,实现统一格式返回?
Gavin teacher's perception of transformer live class - rasa project actual combat e-commerce retail customer service intelligent business dialogue robot microservice code analysis and dialogue experim
Ansible中的inventory主機清單(預祝你我有數不盡的鮮花和浪漫)
File upload vulnerability summary
JS variable case output user name
STM32F103实现IAP在线升级应用程序
【愚公系列】2022年7月 Go教学课程 005-变量
《二》标签