当前位置:网站首页>JUC(八):synchronized小练习
JUC(八):synchronized小练习
2022-07-30 02:45:00 【打工仔呀~】
卖票练习
测试下面代码是否存在线程安全问题,并尝试改正
- 将sell方法声明为synchronized即可
- 注意只将对count进行修改的一行代码用synchronized括起来也不行。对count大小的判断也必须是为原子操作的一部分,否则也会导致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);
// 所以线程的集合
List<Thread> threadList = new ArrayList<>();
// 用来存储买出去多少张票
List<Integer> amountList = new Vector<>();
for (int i = 0; i < 5000; i++) {
Thread t = new Thread(() -> {
{
// 虽说是安全组合,但是操作的不是同一对象,所以无须再次加锁保证原子性
// 买票,分析这里的竞态条件
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会被多个线程共享,必须使用线程安全的实现类。
测试脚本
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
说明:
- 两段没有前后因果关系的临界区代码,只需要保证各自的原子性即可,不需要括起来。
转账练习
测试下面代码是否存在线程安全问题,并尝试改正
- 将transfer方法的方法体用同步代码块包裹,将当Account.class设为锁对象。
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);
}
}
}
这样改正行不行,为什么?
- 不行,因为不同线程调用此方法,将会
锁住不同的对象
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); } } }
边栏推荐
猜你喜欢
随机推荐
[3D检测系列-PointRCNN]复现PointRCNN代码,并实现PointRCNN3D目标检测可视化,包含预训练权重下载链接(从0开始以及各种报错的解决方法)
el-table sum total
信息系统项目管理师核心考点(五十四)配置项分类、状态与版本
RAII技术学习
Hacker News Broadcast | A fake offer steals $625 million
多线程---初阶
win11 自带远程桌面使用(包含非局域网使用以及win11升级为专业版)
YOLOv7的一些理解
【C语言刷LeetCode】592. 分数加减运算(M)
Zero code tools recommended - HiFlow
A plastic bottle of ocean "fantasy drifting"
Using ESP32 construct a ZIGBEE network adapter
matlab用dde23求解带有固定时滞的时滞微分方程
Tibetan Mapping
B. Different Divisors- Codeforces Round #696 (Div. 2)
go jwt use
22/07/21
Kotlin接口
WebSocket在线通信
超详细的MySQL基本操作




![[Notes] Stuttering word segmentation to draw word cloud map](/img/a1/05504ad82d4670386d1cc233291c6a.png)




