Account account=new Account(); savethread newfather = new savethread("亲爹", account); savethread oldfather = new savethread("旧爹", account); savethread wildfather = new savethread("野爹", account); spendthread son1 = new spendthread("小红",account); spendthread son2 = new spendthread("小态",account); spendthread son3 = new spendthread("小从",account); spendthread son4 = new spendthread("小蓝",account); newfather.start(); oldfather.start(); wildfather.start(); son1.start(); son2.start(); son3.start(); son4.start();
时间: 2024-03-07 18:48:35 浏览: 120
这段代码中创建了一个 Account 对象,然后分别创建了三个存钱线程 savethread 和四个取钱线程 spendthread,它们共同操作同一个 Account 对象。
其中,savethread 线程通过调用 Account 对象的存钱方法 save() 来增加账户余额,而 spendthread 线程通过调用 Account 对象的取钱方法 spend() 来减少账户余额。
由于多个线程同时对同一个 Account 对象进行操作,可能会出现线程安全问题,比如数据不一致、死锁等问题。因此需要在 Account 对象的存钱和取钱方法中使用 synchronized 关键字,来实现线程安全。
具体实现可以参考如下代码:
```
class Account {
private int balance = 0;
public synchronized void save(int money) {
balance += money;
System.out.println(Thread.currentThread().getName() + " 存入 " + money + " 元,余额为:" + balance);
}
public synchronized void spend(int money) {
if (balance >= money) {
balance -= money;
System.out.println(Thread.currentThread().getName() + " 取出 " + money + " 元,余额为:" + balance);
} else {
System.out.println(Thread.currentThread().getName() + " 余额不足,取款失败!");
}
}
}
class savethread extends Thread {
private Account account;
public savethread(String name, Account account) {
super(name);
this.account = account;
}
@Override
public void run() {
for (int i = 0; i < 5; i++) {
int money = (int) (Math.random() * 1000);
account.save(money);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class spendthread extends Thread {
private Account account;
public spendthread(String name, Account account) {
super(name);
this.account = account;
}
@Override
public void run() {
for (int i = 0; i < 5; i++) {
int money = (int) (Math.random() * 1000);
account.spend(money);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Main {
public static void main(String[] args) {
Account account = new Account();
savethread newfather = new savethread("亲爹", account);
savethread oldfather = new savethread("旧爹", account);
savethread wildfather = new savethread("野爹", account);
spendthread son1 = new spendthread("小红", account);
spendthread son2 = new spendthread("小态", account);
spendthread son3 = new spendthread("小从", account);
spendthread son4 = new spendthread("小蓝", account);
newfather.start();
oldfather.start();
wildfather.start();
son1.start();
son2.start();
son3.start();
son4.start();
}
}
```
阅读全文