不安全买票
package com.jia.lesson;
import java.security.PrivateKey;
//不安全的买票
public class UnsafeBuyTicket {
public static void main(String[] args) {
BuyTicket buyTicket = new BuyTicket();
new Thread(buyTicket,"me").start();
new Thread(buyTicket,"you").start();
new Thread(buyTicket,"he").start();
}
}
class BuyTicket implements Runnable{
private int ticketNumbers=10;
boolean flag=true;
@Override
public void run() {
//买票
while (flag){
try {
buy();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void buy() throws InterruptedException{
//判断是否有票
if (ticketNumbers<1){
flag=false;
return;
}
Thread.sleep(10000);//出现有人拿到同一张票,是因为延时太低
System.out.println(Thread.currentThread().getName()+"拿到"+ticketNumbers--);
}
}
不安全取钱
package com.jia.lesson;
//不安全取钱
//两个人取钱,账户
public class UnsafeBank {
public static void main(String[] args) {
Account account = new Account("结婚",50);
Bank bank1 = new Bank(account,50,"me");
Bank bank2 = new Bank(account,50,"you");
bank1.start();
bank2.start();
}
}
//账户
class Account{
int money;//余额
String card;//卡名
public Account(String card, int money) {
this.money = money;
this.card = card;
}
}
//银行:模拟取款
class Bank extends Thread{
Account account;//账户
//取了多少钱
int drawingMoney;
//现在手里多少钱
int nowMoney;
public Bank(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(this.getName()+"现金"+nowMoney);
System.out.println(account.card+"余额:"+account.money);
}
}
线程不安全
package com.jia.lesson;
import java.util.ArrayList;
import java.util.List;
//线程不安全的集合
public class UnsafeList {
public static void main(String[] args) {
ArrayList<Object> objects = new ArrayList<>();//数组列表,对象
for (int i = 0; i < 100; i++) {
new Thread(()->{
objects.add(Thread.currentThread().getName());
}).start();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(objects.size());
}
}