Java三大线程不安全案例
案例一 :多个线程同时买票出现同一张票和负票情况
//不安全的买票
public class ExampleUnsafe01 {
public static void main(String[] args) {
Buyticket station = new Buyticket();
new Thread(station,"小明").start();
new Thread(station,"小马").start();
new Thread(station,"小胡").start();
}
}
class Buyticket implements Runnable{
//票
int ticketNum = 10;
//外部停止方式
boolean flag = true;
@Override
public void run() {
//买票
while (flag){
try {
buy();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void buy() throws InterruptedException {
//判断是否有票
if (ticketNum<=0){
flag = false;
}
//模拟延时
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName() + "抢到了第" + ticketNum-- + "张票");
}
}
运行结果:
小马抢到了第10张票
小明抢到了第8张票
小胡抢到了第9张票
小胡抢到了第7张票
小马抢到了第7张票
小明抢到了第7张票
小明抢到了第6张票
小胡抢到了第5张票
小马抢到了第6张票
小明抢到了第4张票
小马抢到了第3张票
小胡抢到了第2张票
小明抢到了第1张票
小胡抢到了第0张票
小马抢到了第1张票
小明抢到了第-1张票
案例二:两个人同时对一个银行账户进行操作出现账户负数情况
package Thread;
//不安全的取钱
//两个人去银行取钱,同一个账户
public class ExampleUnsafe02 {
public static void main(String[] args) {
Account account = new Account(100,"私房钱");
Bank you = new Bank(account,50,"你");
Bank girlfriend = new Bank(account,100,"女朋友");
you.start();
girlfriend.start();
}
}
//账户
class Account{
int money;
String name;
public Account(int money,String name) {
this.money = money;//账户里的钱
this.name = name;//账户名字
}
}
//银行
class Bank extends Thread{
Account account;//账户
int getMoney;//取走的钱
int nowmoney;//记录现在手里的钱
public Bank(Account account,int getMoney,String name) {
super(name);
this.account = account;
this.getMoney = getMoney;
}
//取钱
@Override
public void run() {
//判断账户里还有没有钱
if (account.money - getMoney < 0){
System.out.println(Thread.currentThread().getName()+ "要取钱但是钱不够了");
return;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//账户余额 = 账户余额 - 你取走的钱
account.money = account.money - getMoney;
//现在手里的钱 = 现在手里的钱 + 取走的钱
nowmoney = nowmoney + getMoney;
System.out.println(account.name + "余额为" + account.money);
System.out.println(Thread.currentThread().getName() + "手里的钱为" + nowmoney);
}
}
运行结果:
私房钱余额为-50
你手里的钱为50
私房钱余额为-50
女朋友手里的钱为100
案例三:将多个线程添加进一个集合出现“卡位”现象
import java.util.ArrayList;
import java.util.List;
//线程不安全的集合
public class ExampleUnsafe03 {
public static void main(String[] args) {
List<String> threadList = new ArrayList<String>();
for (int i = 0; i < 1000; i++) {
new Thread(()->{
threadList.add(Thread.currentThread().getName());
}).start();
}
System.out.println(threadList.size());
}
}
运行结果:
993