1. 不安全的买票
public class Tiket implements Runnable {
static int tiket = 10;
boolean flag = true;
@Override
public void run() {
while(flag) buy();
}
public void buy() {
//模拟买票
if (tiket <= 0) {flag=false;return;}
try {
Thread.sleep(100);
} catch (InterruptedException e) { //尝试解除阻塞异常
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "抢到了第" + tiket-- + "张票!");
}
public static void main(String[] args) {
Tiket tiket1=new Tiket();
new Thread(tiket1,"黄牛").start();
new Thread(tiket1,"老师").start();
new Thread(tiket1,"我").start();
}
}
输出结果:
由于线程不同步,出现了取的票号相同,以及取出的票不存在的现象。
2. 不安全的银行(两个人取钱)
public class UnsafeBank {
public static void main(String[] args) {
Account account=new Account(100,"结婚基金");
Draw boy=new Draw(account,50,"boy");
Draw girl=new Draw(account,100,"girl");
boy.start();
girl.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; //现在手里有多少钱
String name;
public Draw(Account account,int drawingMoney,String name){ //现在账户余额,取多少钱,手里有多少钱
this.account=account;
this.drawingMoney=drawingMoney;
this.name=name;
}
@Override
public void run() {
if(this.account.money-this.drawingMoney<0) {System.out.println(this.name+",您的余额不足");return;}
try {
Thread.sleep(3000); //sleep放大问题的发生性,查缺补漏
} catch (InterruptedException e) {
e.printStackTrace();
}
this.account.money-=this.drawingMoney;//找到account堆内存地址,改变银行余额
this.nowMoney+=this.drawingMoney;
System.out.println(this.name+"取到了"+this.nowMoney);
}
}
输出结果:
没有取钱之前银行的余额为100,两人去取钱,由于线程没有同步,导致,两人取的钱总共超出了银行的余额.
3. 不安全的集合
public class UnsafeList {
public static void main(String[] args) throws InterruptedException {
ArrayList list = new ArrayList(); //ArrayList集合线程不安全演示
for (int i = 1; i < 10000; i++) {
new Thread(
() -> { //lamda表达式
list.add(Thread.currentThread().getName());
}
).start();
}
Thread.sleep(1000);
System.out.println(list.size()); //输出结果9998,有一些集合被添加到一个位置,线程不同步,永远不能达到10000
}
}
输出结果:
线程由于不同步导致多个对象被添加到集合中的同一个位置,导致集合的元素个数永远达不到1000.