1. 程式人生 > 其它 >三大執行緒不安全案例

三大執行緒不安全案例

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;
@Override
public void run() {
//買票
while (flag){
try {
buy();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void buy() throws InterruptedException{
//判斷是否有票
if(ticketNums<=0){
return;
}
//買票
Thread.sleep(1000);

System.out.println(Thread.currentThread().getName()+"拿到"+ticketNums--);
}
}

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;
}

//取錢的方法
@Override
public void run() {
//判斷是否還有錢
if (account.money-drawingMoney<0){
System.out.println(Thread.currentThread().getName()+"錢不夠,錢取不了");
return;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}

//卡內餘額=餘額-你取的錢
account.money=account.money-drawingMoney;
//你手裡的錢
nowMoney=nowMoney+drawingMoney;

System.out.println(account.name+"餘額為:"+account.money);
System.out.println(this.getName()+"手裡的錢"+nowMoney);
}
}

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());
}
}