不喜勿喷,学习笔记,新手制作
存放数据
public class Account {
private String actno;
private double balance;
public Account() {
}
public Account(String actno, double balance) {
this.actno = actno;
this.balance = balance;
}
public String getActno() {
return actno;
}
public void setActno(String actno) {
this.actno = actno;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public void winthdraw(double money){
synchronized (this){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.setBalance(this.getBalance() - money);
}
}
public void pls(double money){
synchronized (this){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.setBalance(this.getBalance() + money);
}
}
}
运用多线程制作提款方法,只import了Scanner
public class xctest9 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Account account = null;
System.out.println("请输入账户名和账户初始金额");
String str = null;
int num = 0;
while (scanner.hasNext()) {
str = scanner.nextLine();
System.out.println("账户名为:"+str);
try {
num = scanner.nextInt();
}catch (Exception e){
System.out.println("账户初始金额不能为字符");
continue;
}
if (!(str.isEmpty())||!(num == 0)){
account = new Account(str,num);
break;
}
}
Thread t1 = new Thread(new MyRunnable9(account));
t1.setName("t1");
t1.start();
}
}
class MyRunnable9 implements Runnable{
private double mout ;
private String str;
private Account act ;
public MyRunnable9(Account act){
this.act = act;
}
@Override
public void run() {
System.out.println("存款取款操作开始,余额为:"+act.getBalance()+" exit退出 ");
System.out.println("+ <数字> 是存款 - <数字> 是取款");
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
this.str =scanner.nextLine();
try {
this.mout = Double.parseDouble(str.substring(1));
}catch (Exception e){
if(!(this.str.equals("exit"))){
System.out.println("字符串错误!请输入<指令><数字>");
continue;
}
}
System.out.println("余额为" + act.getBalance());
if (str.startsWith("+")) {
act.pls(this.mout);
System.out.println("存放"+this.mout+"元成功,余额为" + act.getBalance());
} else if (str.startsWith("-")) {
if (act.getBalance() - this.mout <= 0){
System.out.println("余额不足");
}else{
act.winthdraw(this.mout);
System.out.println("取出"+this.mout+"元成功,余额为" + act.getBalance());
}
}else if(str.equals("exit")){
System.out.println("结束成功");
return;
} else {
System.out.println("请在数字前加上正确的指令:+ 是存 -是取");
}
}
}
}