Java 多线程(七)三大不安全案例
一,买票
//不安全买票
public class UnsafeBuyTickets {
public static void main(String[] args) {
BuyTickets buyTickets = new BuyTickets();
new Thread(buyTickets,"黄牛").start();
new Thread(buyTickets,"平民").start();
new Thread(buyTickets,"贵族").start();
new Thread(buyTickets,"皇室").start();
}
}
class BuyTickets implements Runnable{
private int ticketsNum = 10;
boolean flag = true;
@Override
public void run() {
while(flag){
buy();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void buy (){
if (ticketsNum <=0){
flag = false;
return;
}
System.out.println(Thread.currentThread().getName()+"拿到了第"+ticketsNum--+"张票!");
}
}
结果会看到负数:
二,取钱
//不安全取钱 public class UnsafeBank { public static void main(String[] args) { //账户 Account account = new Account(100, "结婚基金"); Draw you = new Draw(account,50,"你"); Draw girlFriend = new Draw(account,100,"girlFriend"); you.start(); girlFriend.start(); } } //账户 class Account{ int money ; String name; public Account(int money, String name) { this.money = money; this.name = name; } } //取钱 class Draw extends Thread{ Account account;//账户 int drawingMoney;//取多少钱 int nowMoney;//手里多少钱 public Draw(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(Thread.currentThread().getName()+"余额不足"); return; } //sleep try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } //卡内余额=卡里余额-取出钱 account.money = account.money-drawingMoney; //手里钱=手里钱+取出钱 nowMoney = nowMoney+drawingMoney; System.out.println(account.name+"余额为:"+account.money); //Thread.currentThread().getName()等价于this.getName() System.out.println(this.getName()+"手里的钱:"+nowMoney); } }
结果看到负数:
三,不安全集合
//线程不安全的集合 public class UnsafeList { public static void main(String[] args) throws InterruptedException { List<String> list = new ArrayList<String>(); for (int i = 0; i < 10000; i++) { new Thread(()->{ list.add(Thread.currentThread().getName()); }).start(); } Thread.sleep(3000); System.out.println(list.size()); } }
结果看到集合中数量不够应该是有10000个: