三大執行緒不安全案例
阿新 • • 發佈:2021-07-29
1.不安全買票
package syn;
//不安全買票
public class UnsafeBuyTicket {
public static void main(String[] args) {
BuyTicket buyTicket=new BuyTicket();
new Thread(buyTicket,"小明").start();
new Thread(buyTicket,"小紅").start();
new Thread(buyTicket,"黃牛黨").start();
}
}
class BuyTicket implements Runnable{
private int ticketNums =10;
boolean flag=true;
2.不安全取錢
package syn;
//不安全取錢
//兩個人去銀行取錢,賬戶
public class UnsafeBank {
public static void main(String[] args) {
Account account=new Account(100,"結婚基金");
Drawing you=new Drawing(account,50,"你");
Drawing girlFriend=new Drawing(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 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;
}
//取錢的方法
3.執行緒不安全的集合
package syn;
import java.util.ArrayList;
import java.util.List;
//執行緒不安全的集合
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(1000);
System.out.println(list.size());
}
}