樣例一
package com.example.demo.thread;
/**
* @projectName: demo
* @package: com.example.demo.thread
* @className: AsyncTest1
* @author:
* @description: 線程不安全示例1
* @date: 2021/12/7 23:54
*/
public class AsyncTest1 {
public static void main(String[] args) {
Ticket ticket = new Ticket();
new Thread(ticket, "學(xué)生").start();
new Thread(ticket, "程序員").start();
new Thread(ticket, "黃牛").start();
}
}
class Ticket implements Runnable {
private int ticketNum = 10;
private boolean flag = true;
@Override
public void run() {
while (flag) {
buyTicket();
}
}
private void buyTicket() {
if (ticketNum <= 0) {
flag = false;
return;
}
System.out.println(Thread.currentThread().getName() + "購買第" + ticketNum + "票捉兴!");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
ticketNum--;
}
}
樣例二
package com.example.demo.thread;
/**
* @projectName: demo
* @package: com.example.demo.thread
* @className: UnsafeBank
* @author:
* @description: 多個(gè)提款機(jī)取票通孽,觀察最終的賬戶余額和到手金額
* @date: 2021/12/8 10:33
*/
public class UnsafeBank {
public static void main(String[] args) {
Account account = new Account("工資卡", 100);
CashMachine cashMachine = new CashMachine(account, 50);
CashMachine cashMachine1 = new CashMachine(account, 100);
new Thread(cashMachine, "張三").start();
new Thread(cashMachine1, "張三老婆").start();
}
}
class Account {
// 卡明
private String name;
// 卡內(nèi)余額
private int money;
public Account(String name, int money) {
this.name = name;
this.money = money;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
}
class CashMachine implements Runnable {
private Account account;
// 共計(jì)取出的金額
private int nowMoney;
// 提款機(jī)中取出的金額
private int getMoney;
public CashMachine(Account account, int getMoney) {
this.account = account;
this.getMoney = getMoney;
}
@Override
public void run() {
if (this.account.getMoney() - getMoney < 0) {
System.out.println(Thread.currentThread().getName() + "卡里余額不足仲义!");
return;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.draw();
}
private void draw() {
// 卡內(nèi)余額
int temp = this.account.getMoney() - getMoney;
this.account.setMoney(temp);
// 手里
this.nowMoney = this.nowMoney + getMoney;
System.out.println(Thread.currentThread().getName() + "取出" + getMoney + "元齐蔽,賬戶余額" + temp + "元产弹,共計(jì)到手" + this.nowMoney + "元");
}
}
賬戶總共100元派歌,最終取出150,提款機(jī)-50