现已有Account
类,拥有
属性:
private int balance
方法:
相应的getter方法。
要求为该类编写:
void deposit(int money)
//存钱,在余额的基础上加上money
void withdraw(int money)
//取钱,在余额的基础上减去money
注意:
- 取钱时如果
balance<0
的时候,会抛出异常。在多线程情况下,如只有一个存钱的线程,但是有多个取钱的线程,很可能会抛出异常。 - 需要编写完整的deposit方法与withdraw的前半部分代码解决该问题。
裁判测试程序:
import java.util.Scanner;
//这里是已有的Account类前半部分的代码
/*这里是deposit代码*/
/*这里是withdraw代码的前半部分*/
if(balance<0) //这里是withdraw代码的后半部分。
throw new IllegalStateException(balance+"");
}
/*系统已有代码,无需关注*/
输入样例:
分别为初始余额、存钱次数、存钱金额
取钱次数、取钱金额。有3个线程。
0 100000 12
100000 4
输出样例:
余额:使用线程跑出的结果。
余额:存钱次数*存钱金额 - 取钱次数*取钱金额*3
0
0
代码:
package com.PTA;
public class Main {
public static void main(String[] args) throws InterruptedException {
Account account = new Account(0);
Thread t1 = new Thread(new Draw(account));
Thread t2 = new Thread(new Draw(account));
Thread t3 = new Thread(new Draw(account));
Thread t4 = new Thread(new deposit(account));
t4.start();
t1.start();
t2.start();
t3.start();
t1.join();
t2.join();
t3.join();
t4.join();
System.out.println(account.getBalance());
}
}
class deposit implements Runnable {
private final Account account;
deposit(Account account) {
this.account = account;
}
@Override
public void run() {
for (int i = 0; i < 100000; i++) {
account.deposit(12);
}
}
}
class Draw implements Runnable {
private final Account account;
public Draw(Account account) {
this.account = account;
}
@Override
public void run() {
for (int i = 0; i < 100000; i++) {
account.withdraw(4);
}
}
}
class Account {
private int balance;
public Account(int balance) {
this.balance = balance;
}
public int getBalance() {
return balance;
}
public synchronized void deposit(int money) {
this.balance += money;
if (this.balance >= 0)
this.notifyAll();
}
public synchronized void withdraw(int money) {
while (this.balance < money) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (this.balance < 0) {
throw new IllegalStateException(balance + "");
}
this.balance -= money;
}
}