java模擬銀行存取錢業務
阿新 • • 發佈:2018-12-30
package cunqianTest;
/*
* 模擬存錢,取錢
* 如果輸入的數字為正數,則為存錢反之取錢
*/
public class Card {
private String name;
private int money;
public Card(String name, int money) {
super();
this.name = name;
this.money = money;
}
public Card() {
super();
}
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;
}
@Override
public String toString() {
return "Card [name=" + name + ", money=" + money + "]";
}
public void add(int money) {
if (money > 0) {// 存錢
this.money = this.money + money;
System.out.println(Thread.currentThread().getName() + " 存了" + money + "\t餘額為:" + this.getMoney());
} else {// 取錢
this.money = this.money + money;
System.out.println(Thread.currentThread().getName() + " 取了" + (-money) + "\t餘額為:" + this.getMoney());
}
}
/*
* 模擬存錢,取錢
* 如果輸入的數字為正數,則為存錢反之取錢
*/
public class Card {
private String name;
private int money;
public Card(String name, int money) {
super();
this.name = name;
this.money = money;
}
public Card() {
super();
}
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;
}
@Override
public String toString() {
return "Card [name=" + name + ", money=" + money + "]";
}
public void add(int money) {
if (money > 0) {// 存錢
this.money = this.money + money;
System.out.println(Thread.currentThread().getName() + " 存了" + money + "\t餘額為:" + this.getMoney());
} else {// 取錢
this.money = this.money + money;
System.out.println(Thread.currentThread().getName() + " 取了" + (-money) + "\t餘額為:" + this.getMoney());
}
}
}
package cunqianTest;
public class CardUtil implements Runnable {
private Card card;
public CardUtil(Card card) {
super();
this.card = card;
}
@Override
public void run() {
int count = 0;
int num;
for (int i = 0; i < 20; i++) {
synchronized (card) {
//減500的作用讓隨機數有機會產生負數
num = (int) (Math.random() * 1000 + 1) - 500;
card.add(num);
}
}
}
}
package cunqianTest;
public class TestCard {
public static void main(String[] args) {
Card card = new Card();
CardUtil util = new CardUtil(card);
CardUtil util2 = new CardUtil(card);
Thread t1 = new Thread(util);
Thread t2 = new Thread(util2);
t1.start();
t2.start();
}
}