当前位置:网站首页>JUC (8) : synchronized little exercise
JUC (8) : synchronized little exercise
2022-07-30 02:50:00 【Working boy~】
卖票练习
测试下面代码是否存在线程安全问题,并尝试改正
- 将sell方法声明为synchronized即可
- Note only paircountOne line of code to modifysynchronizedNot even enclosed.对countThe size determination must also be part of the atomic operation,否则也会导致count值异常.
import lombok.extern.slf4j.Slf4j;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Vector;
@Slf4j
public class ExerciseSell {
public static void main(String[] args) throws InterruptedException {
// 模拟多人买票
TicketWindow window = new TicketWindow(1000);
// So a collection of threads
List<Thread> threadList = new ArrayList<>();
// 用来存储买出去多少张票
List<Integer> amountList = new Vector<>();
for (int i = 0; i < 5000; i++) {
Thread t = new Thread(() -> {
{
// Although it is a safe combination,But the operation is not the same object,So there is no need to lock again to ensure atomicity
// 买票,分析这里的竞态条件
int count = window.sell(randomAmount());
// 统计买票数
amountList.add(count);
}
});
threadList.add(t);
t.start();
}
for (Thread thread : threadList) {
thread.join();
}
// 买出去的票求和
log.debug("销售数量:{}", amountList.stream().mapToInt(c -> c).sum());
// 剩余票数
log.debug("余数:{}", window.getCount());
}
// Random 为线程安全
static Random random = new Random();
// 随机 1~5
public static int randomAmount() {
return random.nextInt(5) + 1;
}
}
class TicketWindow {
private int count;
public TicketWindow(int count) {
this.count = count;
}
public int getCount() {
return count;
}
//在方法上加一个synchronized即可
public int sell(int amount) {
// 临界区 需要保护
if (this.count >= amount) {
this.count -= amount;
return amount;
} else {
return 0;
}
}
}
另外,用下面的代码行不行,为什么?
List<Integer> amountLis = new ArrayList<>();
- 不行,因为amountLis会被多个线程共享,A thread-safe implementation class must be used.
测试脚本
for /L %n in (1,1,10) do java -cp ".;C:\Users\manyh\.m2\repository\ch\qos\logback\logback-classic\1.2.3\logback-classic-1.2.3.jar;C:\Users\manyh\.m2\repository\ch\qos\logback\logback-core\1.2.3\logback-core-1.2.3.jar;C:\Users\manyh\.m2\repository\org\slf4j\slf4j-api\1.7.25\slf4j-api-1.7.25.jar" cn.xiaozheng.n4.exercise.ExerciseSell
for /L %n in (1,1,10) do E:\prolificacy\Java\OpenJDK-11.0.15_9\bin\java.exe -Dfile.encoding=UTF-8 -classpath "E:\CodeDirectory\CodeIDEA\practice-project\juc-demo\target\classes;E:\prolificacy\apache-maven-3.8.4\.maven-respository\ch\qos\logback\logback-classic\1.2.10\logback-classic-1.2.10.jar;E:\prolificacy\apache-maven-3.8.4\.maven-respository\ch\qos\logback\logback-core\1.2.10\logback-core-1.2.10.jar;E:\prolificacy\apache-maven-3.8.4\.maven-respository\org\slf4j\slf4j-api\1.7.32\slf4j-api-1.7.32.jar;E:\prolificacy\apache-maven-3.8.4\.maven-respository\org\projectlombok\lombok\1.18.20\lombok-1.18.20.jar" com.xiaozheng.day1.ExerciseSell
说明:
- Two pieces of critical section code with no causal relationship,Just need to guarantee their atomicity,Brackets are not required.
转账练习
测试下面代码是否存在线程安全问题,并尝试改正
- 将transferThe method body of the method is wrapped in a synchronized block,将当Account.classset as lock object.
public class ExerciseTransfer {
public static void main(String[] args) throws InterruptedException {
Account a = new Account(1000);
Account b = new Account(1000);
Thread t1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
a.transfer(b, randomAmount());
}
}, "t1");
Thread t2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
b.transfer(a, randomAmount());
}
}, "t2");
t1.start();
t2.start();
t1.join();
t2.join();
// 查看转账2000次后的总金额
log.debug("total:{}",(a.getMoney() + b.getMoney()));
}
// Random 为线程安全
static Random random = new Random();
// 随机 1~100
public static int randomAmount() {
return random.nextInt(100) +1;
}
}
class Account {
private int money;
public Account(int money) {
this.money = money;
}
public int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
public void transfer(Account target, int amount) {
if (this.money > amount) {
this.setMoney(this.getMoney() - amount);
target.setMoney(target.getMoney() + amount);
}
}
}
这样改正行不行,为什么?
- 不行,Because different threads call this method,将会
Lock different objects
public synchronized void transfer(Account target, int amount) {
if (this.money > amount) {
this.setMoney(this.getMoney() - amount);
target.setMoney(target.getMoney() + amount);
}
}
// 等价于
public void transfer(Account target, int amount) {
synchronized (this) {
// 临界区
if (this.money > amount) {
this.setMoney(this.getMoney() - amount);
target.setMoney(target.getMoney() + amount);
}
}
}
正确解决,锁Class
public void transfer(Account target, int amount) { synchronized (Account.class) { // 临界区 if (this.money > amount) { this.setMoney(this.getMoney() - amount); target.setMoney(target.getMoney() + amount); } } }
边栏推荐
- 新手入门C#:实现简易的计算器功能
- 成功解决pydotplus.graphviz.InvocationException: GraphViz‘s executables not found
- 实现批量导出功能
- 绘制概率密度图
- Not enough information to list load addresses in the image map. (STM32 compilation error)
- Drawing Problem Log
- (RCE)远程代码/命令执行漏洞漏洞练习
- 机器学习1一回归模型(一)
- STM32L4R9ZIY6PTR STM32L4 high-performance embedded-MCU
- 再度入围|“国产化”大潮来袭,汉得助力乘风破浪!
猜你喜欢
随机推荐
自动配置和 thymeleaf模板引擎
使用SqlSessionFactory工具类抽取
Using ESP32 construct a ZIGBEE network adapter
每日优鲜生死劫:被曝清退大部分员工 仍未递交年报(附音频)
【高性能计算】openMP
成功解决pydotplus.graphviz.InvocationException: GraphViz‘s executables not found
3种实现文本复制功能的方法
乖宝宠物IPO过会:年营收25.75亿 KKR与君联是股东
Simple Operations on Sequence
快速入门jsp
go grpc custom interceptor
ButtonStyle, MaterialStateProperty learned by flutter
一个塑料瓶的海洋“奇幻漂流”
[Notes] Stuttering word segmentation to draw word cloud map
org.apache.ibatis.binding.BindingException Invalidbound statement (not found)的解决方案和造成原因分析(超详细)
DAP data processing process
躲避雪糕刺客?通过爬虫爬取雪糕价格
JS history.back() go(-1) Location 跳转 重新加载页面 get请求 返回顶部 bom
JUC(四):简记线程的五/六种状态
华宝新能通过注册:拟募资近7亿 营收增加利润反而下降









