java编程题: 采用多线程机制模拟汇款业务。定义一银行类可接受顾客的汇款,其属性count用于存储账户金额。现有两名顾客,每人分三次、每次100元将钱汇入count。每进行一次汇款,便输出汇款人和账户总额
时间: 2023-12-03 10:03:47 浏览: 50
好的,这是一道Java编程题,需要用到多线程机制来模拟汇款业务。下面是代码实现:
```java
public class Bank {
private int count = 0;
public synchronized void remit(String name) {
for (int i = 0; i < 3; i++) {
count += 100;
System.out.println(name + " remit 100, count is " + count);
}
}
}
public class Customer implements Runnable {
private Bank bank;
private String name;
public Customer(Bank bank, String name) {
this.bank = bank;
this.name = name;
}
@Override
public void run() {
bank.remit(name);
}
}
public class Main {
public static void main(String[] args) {
Bank bank = new Bank();
Customer customer1 = new Customer(bank, "Customer1");
Customer customer2 = new Customer(bank, "Customer2");
new Thread(customer1).start();
new Thread(customer2).start();
}
}
```
在Bank类中,我们定义了一个属性count来存储账户金额,remitt方法用来接受顾客的汇款。这里使用了synchronized关键字来实现线程同步。
在Customer类中,我们定义了bank和name两个属性,分别代表银行和顾客的名字。在run方法中,调用了bank的remit方法,来模拟顾客汇款的过程。
在Main类中,我们创建了一个银行对象和两个顾客对象,并启动了两个线程来模拟汇款业务的过程。
每进行一次汇款,都会输出汇款人和账户总额,最终结果如下:
```
Customer1 remit 100, count is 100
Customer2 remit 100, count is 200
Customer1 remit 100, count is 300
Customer2 remit 100, count is 400
Customer1 remit 100, count is 500
Customer2 remit 100, count is 600
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)