当前位置:网站首页>线程安全问题
线程安全问题
2022-07-01 04:46:00 【洋啊桑815】
线程安全问题指的是:多个线程同时操作一个共享资源的时候,可能会出现业务安全问题,
一般发生与同事修改同一个共享资源时。
我一下面这段代码举例:
首先是这一个共享的账户类People,它包含updateMoney()方法,用于修改里面存储的金额Money,
public class People {
private double money;
public People() {
}
public People(double money) {
this.money = money;
}
public double getMoney() {
return money;
}
public void setMoney(double money) {
this.money = money;
}
public void updateMoney(double price){
System.out.println("当前线程已经连接账户,账户余额:"+money);
System.out.println(Thread.currentThread().getName()+"取钱:"+price);
money-=price;
System.out.println("账户余额:"+money);
}
}
其次是它的主类;
public class Test1 {
public static void main(String[] args) throws Exception {
People people=new People(1000.0);//在账户中放入1000元
//创建两个线程
new MyThread(people,"1号").start();
new MyThread(people,"2号").start();
}
}
class MyThread extends Thread{
private People people;
public MyThread(People people,String name) {
super(name);
this.people=people;
}
@Override
public void run(){
//调用People的方法,从中取出1000元;
people.updateMoney(1000.0);
}
}当然,这是有问题的,创建的两个线程同时执行,它们会同时从People中取出1000元,而本来People中就只有1000元,name就会造成以下的结果;
当前线程已经连接账户,账户余额:1000.0
当前线程已经连接账户,账户余额:1000.0
2号取钱:1000.0
1号取钱:1000.0
账户余额:0.0
账户余额:-1000.0
这样就造成了线程安全问题
边栏推荐
- STM32扩展版 按键扫描
- Seven crimes of counting software R & D Efficiency
- Leecode record 1351 negative numbers in statistical ordered matrix
- Pytorch(三) —— 函数优化
- LM small programmable controller software (based on CoDeSys) note 20: PLC controls stepping motor through driver
- Codeworks round 449 (Div. 1) C. Kodori tree template
- 分布式-总结列表
- JS rotation chart
- The longest increasing subsequence and its optimal solution, total animal weight problem
- 神经网络-使用Sequential搭建神经网络
猜你喜欢

Kodori tree board

How to do the performance pressure test of "Health Code"

RuntimeError: mean(): input dtype should be either floating point or complex dtypes.Got Long instead

Common methods in transforms

技术分享| 融合调度中的广播功能设计

2022 gas examination question bank and online simulation examination

CF1638E. Colorful operations Kodori tree + differential tree array

VIM简易使用教程

I also gave you the MySQL interview questions of Boda factory. If you need to come in and take your own

VR线上展览所具备应用及特色
随机推荐
Take a cold bath
最长递增子序列及最优解、动物总重量问题
LM小型可编程控制器软件(基于CoDeSys)笔记二十:plc通过驱动器控制步进电机
Kodori tree board
1076 Forwards on Weibo
分布式锁的实现
pytorch神经网络搭建 模板
C read / write application configuration file app exe. Config and display it on the interface
Software testing needs more and more talents. Why do you still not want to take this path?
Odeint et GPU
LeetCode_ 28 (implement strstr())
Leecode question brushing record 1310 subarray XOR query
无器械健身
Why is Internet thinking not suitable for AI products?
Construction of Meizhou nursing laboratory: equipment configuration
Simple implementation of slf4j
RuntimeError: “max_pool2d“ not implemented for ‘Long‘
JVM栈和堆简介
总结全了,低代码还需要解决这4点问题
常用的Transforms中的方法