JAVA取钱多线程实验_java – 如何在简单的现金存款提取程序中处理多线程

帐户类

public class Account {

public static Account account;

private static int balance = 1000;

private static Person person;

private Account() {

}

public static Account getAccount(Person p) {

if (account == null) {

account = new Account();

}

Account.person = p;

return account;

}

public static int getBal() {

return balance;

}

public synchronized void withdraw(int bal) {

try {

if (balance >= bal) {

System.out.println(person.getName() + " " + "is try to withdraw");

try {

Thread.sleep(100);

} catch (Exception e) {

e.printStackTrace();

}

balance = balance - bal;

System.out.println(person.getName() + " " + "is complete the withdraw");

} else {

System.out.println(person.getName() + " " + "doesn't have enough money for withdraw ");

}

System.out.println(person.getName() + " " + " withdraw Rs." + balance);

} catch (Exception e) {

e.printStackTrace();

}

}

public synchronized void deposit(int bal) {

try {

if (bal > 0) {

System.out.println(person.getName() + " " + " is try to deposit");

try {

Thread.sleep(100);

} catch (Exception e) {

e.printStackTrace();

}

balance = balance + bal;

System.out.println(person.getName() + " " + "is complete the deposit");

} else {

System.out.println(person.getName() + " " + "doesn't have enough money for deposit");

}

System.out.println(person.getName() + " " + " deposit Rs." + balance);

} catch (Exception e) {

e.printStackTrace();

}

}}

人类

public class Person {

private String name;

public Person(String name) {

this.name = name;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

@Override

public String toString() {

return name;

}}

ThreadExercise类

public class ThreadExercise extends Thread implements Runnable {

private Person person;

public ThreadExercise(Person p) {

this.person = p;

}

public static void main(String[] args) {

ThreadExercise ts1 = new ThreadExercise(new Person("person 1"));

ts1.start();

ThreadExercise ts2 = new ThreadExercise(new Person("person 2"));

ts2.start();

ThreadExercise ts3 = new ThreadExercise(new Person("person 3"));

ts3.start();

}

@Override

public void run() {

for (int i = 0; i < 3; i++) {

try {

Account acc = Account.getAccount(person);

acc.withdraw(100);

try {

Thread.sleep(200);

} catch (InterruptedException ex) {

Logger.getLogger(ThreadExercise.class.getName()).log(Level.SEVERE, null, ex);

}

if (acc.getBal() < 0) {

System.out.println("account is overdrawn!");

}

acc.deposit(200);

} catch (Exception e) {

e.printStackTrace();

}

}

System.out.println("Final Acc balance is Rs." + Account.getBal());

}}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值