老师,麻烦看一下
package com.practice1;
/**
* @author 谭昌
* @date 2021/4/18
*/
public class Bank {
//账户
private String account;
//余额
private double balance;
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
@Override
public String toString() {
return "Bank{" +
"account='" + account + '\'' +
", balance=" + balance +
'}';
}
public Bank(String account, double balance) {
this.account = account;
this.balance = balance;
}
//存款
public synchronized void SaveAccount(){
//获取当前余额
double balance = getBalance();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//修改余额
balance+=100;
setBalance(balance);
System.out.println("存款之后的金额:"+balance);
}
//取款
public void TakeAccount() {
synchronized (this) {
//获取余额
double balance = getBalance();
//修改余额
balance-=200;
setBalance(balance);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("取款之后的余额:" + balance);
}
}
}
package com.practice1;
import java.util.Scanner;
/**
* @author 谭昌
* @date 2021/4/18
*/
public class SaveAccount implements Runnable{
private Bank bank;
@Override
public void run() {
/* Scanner sc = new Scanner(System.in);
System.out.print("请放入您的钞票:");
double saveMoney = sc.nextDouble();*/
bank.SaveAccount();
}
public SaveAccount(Bank bank) {
this.bank = bank;
}
}
package com.practice1;
import java.util.Scanner;
/**
* @author 谭昌
* @date 2021/4/18
*/
public class TakeAccount implements Runnable{
private Bank bank;
public TakeAccount(Bank bank) {
this.bank = bank;
}
@Override
public void run() {
/* Scanner sc = new Scanner(System.in);
System.out.print("您要取走的钞票:");
double TakeMoney = sc.nextDouble();*/
bank.TakeAccount();
}
}
package com.practice1;
/**
* @author 谭昌
* @date 2021/4/18
*/
public class BankTest {
public static void main(String[] args) {
Bank bank = new Bank("农业银行", 1000);
SaveAccount sa = new SaveAccount(bank);
TakeAccount ta = new TakeAccount(bank);
Thread t1 = new Thread(sa, "t1");
Thread t2 = new Thread(ta,"t2");
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(bank);
}
}
在Bank类中,为什么我用修改余额用setBalance(balance-200),setBalance(banlance+100),和老师的结果不一样了
16
收起
正在回答
2回答
同学你好,同学说的是出现了如下结果吧,比如
如果是,那同学代码应该是这样书写的
如上所示,对应展示的就会出现问题,只展示初次获取的局部变量balance。
当直接获取成员属性balance,直接执行计算,就可以了,比如:
祝学习愉快!
java工程师2020版
- 参与学习 人
- 提交作业 9393 份
- 解答问题 16556 个
综合就业常年第一,编程排行常年霸榜,无需脱产即可学习,北上广深月薪过万 无论你是未就业的学生还是想转行的在职人员,不需要基础,只要你有梦想,想高薪
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星