以下为全部代码
//Account类
package c;
/**
* @author
* @create 2022-08-0220:59
*/
public class Account {
//共享的那个账户
//属性
private double balance;
//getter&&setter
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
//构造器
public Account() {
}
public Account(double balance) {
this.balance = balance;
}
//方法
//在账户中就提供了存钱的方法并且加锁
//变为安全线程
public synchronized void add(double money) {
if (money < 0 || getBalance() < money) {
System.out.println("非法数据或者余额不足,取钱失败");
} else {
for (int i = 0; i < 3; i++) {
double ppp = getBalance() + money;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
setBalance(ppp);
System.out.println(Thread.currentThread().getName()+"存钱成功,余额为:" + getBalance());
}
}
}
}
//Customer类
package c;
/**
* @author
* @create 2022-08-0221:13
*/
public class Customer implements Runnable {//继承于Thread类
//属性
private Account a1;//定义Account类型的属性a1
//此外与Account类没有其他关系,其他关系是指继承等关系
//构造器
public Customer(){
}
public Customer(Account a1){//通过构造器实例化Account类
this.a1=a1;
}
//方法
//因为在Customer类中继承Thread,因此需要重写run方法
//不知道有啥子问题,无法自动出现@Override,此处为手动添加
@Override
public void run(){
a1.add(1000);//此处通过在Customer类中实现Account类.出我们需要的方法
}
}
//测试类
package c;
/**
* @author
* @create 2022-08-0221:21
*/
public class AccountTest {
Account a1=new Account(1000);//设置原账户余额为1000元
Customer c1=new Customer(a1);
//因为此处用的是Customer extends Thread,所以需要new的是Customer
Thread t1=new Thread(c1);
Thread t2=new Thread(c1);
//建立两个进程
//此处应该是因为没有正确进行run方法的重写,导致无法start
t1.start();
t2.start();
}
///20220803
应该是因为电脑不对,今天正常了