public class UnsafeBuyTicket {
public static void main(String[] args) {
BuyTicket b = new BuyTicket();
new Thread(b,"老黄牛").start();
new Thread(b,"网友").start();
new Thread(b,"自己").start();
}
}
class BuyTicket implements Runnable{
// 票
private int ticetNum = 10;
// 外部停止方式
boolean flag = true;
@Override
public void run() {
// 买票
while (flag){
buy();
}
}
private void buy(){
// 判断是否有票
if(ticetNum<=0){
flag = false;
return;
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 买票
System.out.println(Thread.currentThread().getName()+"拿到"+ticetNum--);
}
}
// 不安全的取钱
// 两个人去银行账户,取钱
public class UnsafeBank {
public static void main(String[] args) {
// 账户
Account account = new Account("项目基金",100);
Drawing you = new Drawing(account,50,"组长");
Drawing my = new Drawing(account,80,"组员");
you.start();
my.start();
}
}
class Account{
String name;
int money;
public Account(String name, int yue) {
this.name = name;
this.money = yue;
}
}
// 银行:模拟取钱
class Drawing extends Thread{
Account account;// 账户
// 取了多少钱
int drawingMoney;
// 现在手里有多少钱
int nowMoney;
public Drawing(Account account,int drawingMoney,String name){
super(name);
this.account = account;
this.drawingMoney = drawingMoney;
}
// 取钱
@Override
public void run() {
// 判断有没有钱
if (account.money-drawingMoney<0){
System.out.println(this.getName()+"没钱了,取不了");
return;
}
// sleep可以放大问题的发生性
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 卡内余额 = 余额 - 你取的钱
account.money -= drawingMoney;
// 你手里的钱
nowMoney += drawingMoney;
System.out.println(account.name+"余额为:"+account.money);
System.out.println(this.getName()+"手里的钱"+nowMoney);
}
}
public class UnsafeList {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
for(int i = 0;i<10000;i++){
new Thread(()->{
list.add(Thread.currentThread().getName());
}).start();
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}
}
为什么会出现这样的情况呢?
因为集合添加的时候,如果中间有重复,它就会添加替换到同一个地方,导致循环走完数组数据不足的情况。
如果案例三for循环里的lamdba表达式不清楚
这里给大家把不安全案例修改为安全案例
Java-----多线程【同步方法 与 不安全案例转换为安全案例】
Afrikaans:af Albanian:sq Basque:eu Belarusian:be Bulgarian:bg Catalan:ca Ch...
本文分享自华为云社区《 架构可视化支撑系统演进探索 》原文作者无名小溪。 随着...
今天给大家分享四个在实际开发中,比较实用的SQL Server脚本函数,希望对大家能...
ajax传送json格式数据,关键是指定contentType,data要是json格式 如果是restful...
最近在和团队规划OKR目标的时候,我们讨论了很多问题,我先抛砖引玉,列举了一些...
一、导读 本文主要介绍Redhat7.6系统安装oracle 12201版本RAC的一些坑以及避坑方...
Linux 发行版的爱好者们又有全新的 Linux 可以体验了,日前一款名为 TeLOS 的 Li...
Eval 计算一个表达式的值并返回结果。 语法:[result = ]eval_r(expression_r) e...
如果你想对使用手机,平板电脑和辅助技术的用户隐藏某些内容,而只对键盘用户显...
一. RabbitMQ 简介 MQ全称为Message Queue, 消息队列(MQ)是一种应用程序对应用...