不安全案例1
三人同时抢10张火车票
package syn; public class BuyTicket { public static void main(String[] args) { My my = new My(); new Thread(my,"aa").start(); new Thread(my,"ab").start(); new Thread(my,"ac").start(); } } class My implements Runnable{ int ticket=10; boolean flag=true; @Override public void run() { while (flag) { try { //延迟可以扩大问题的严重性 Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } buTicket(); } } private void buTicket(){ if (ticket <= 0) { flag = false; return;} System.out.println(Thread.currentThread().getName() + "买到了->" + ticket--); } }
不安全案例2
package syn; public class SafeBank { public static void main(String[] args) { Card card = new Card(100,"结婚基金"); YinHang yinHang = new YinHang(card,100,"你"); YinHang yh = new YinHang(card,50,"妻子"); yh.start(); yinHang.start(); } } class Card{ int money; String name; public Card(int money, String name) { this.money = money; this.name = name; } } class YinHang extends Thread{ Card card; int qje; int sje; public YinHang(Card card, int qje, String name) { super(name); this.card = card; this.qje = qje; } @Override public void run() { if (card.money-qje<0) { System.out.println("钱不够了"); return; } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } card.money = card.money - qje; System.out.println(Thread.currentThread().getName() + "取了" + qje + "还剩" + card.money); } }
两个人同时去银行取钱