package com.itheima.d3_thread_safe; public class Account { private String
cardId; private double money; // Account balance public Account() { } public
Account(String cardId, double money) { this.cardId = cardId; this.money =
money; } /** * Xiao Ming Xiao Hong * @return */ public void drawMoney(double money) {
//0. First get who will withdraw the money , The name of the thread is the name of the person String name = Thread.currentThread().getName();
//1. Determine whether the account has enough money if(this.money >= money){ //2. Withdraw money System.out.println(name +
" To withdraw money successfully , Spit out :" + money); //3. Update balance this.money -= money; System.out.println(name +
" Remaining after withdrawal :" + this.money); }else{ //4. Sorry, your credit is running low System.out.println(name + " Come and get the money , Sorry, your credit is running low !");
} } public String getCardId() { return cardId; } public void setCardId(String
cardId) { this.cardId = cardId; } public double getMoney() { return money; }
public void setMoney(double money) { this.money = money; } } package
com.itheima.d3_thread_safe; /** * Thread class for withdrawal */ public class DrawThread extends
Thread{ // Account object to be processed . private Account acc; public DrawThread(Account acc, String
name){ super(name); this.acc = acc; } @Override public void run() { // Xiao Ming Xiao Hong
: Withdrawal acc.drawMoney(100000); } } package com.itheima.d3_thread_safe; public
class ThreadDemo { public static void main(String[] args) {
//1. Define thread class , Create a shared account object Account acc = new Account("ICBC-111",100000);
//2. establish 2 Thread objects , Xiao Ming and Xiao Hong came in at the same time . new DrawThread(acc," Xiao Ming ").start(); new
DrawThread(acc," Xiao Hong ").start(); } }

 

Technology