高分悬赏JAVA的一道题!!大神往这看
设计多线程事先银行账户的存/取款过程。设计3个类:账户类Account、存款线程类Save、取款线程类Fetch(8分)。账户类Account记录储户名和金额,提供存款方...
设计多线程事先银行账户的存/取款过程。设计3个类:账户类Account、存款线程类Save、取款线程类Fetch(8分)。账户类Account记录储户名和金额,提供存款方法put()和取款方法get()(5分)。Save和Fetch类分别提供对指定账户的存/取款操作(5分)。定义测试类进行测试,要求保证存取款的正确执行(3分)。
展开
1个回答
展开全部
public class Account {
private String name;
private double money;
private byte[] LOCK = new byte[0];
public Account(String name) {
this(name, 0);
}
public Account(String name, double money) {
super();
this.name = name;
this.money = money;
}
public void put(double money){
synchronized(LOCK){
this.money +=money;
}
}
public double get(double money){
synchronized(LOCK){
if(this.money < money){
System.out.println("余额不足!");
return 0;
} else {
this.money -=money;
return money;
}
}
}
public String toString(){
return "[name="+name+",money="+money+"]";
}
}
public class Fetch implements Runnable {
private Account account;
private Random r = new Random();
public Fetch(Account a){
account = a;
}
@Override
public void run() {
if(account != null){
int i = 0;
while(true){
try {
TimeUnit.MILLISECONDS.sleep(r.nextInt(1000));
i = r.nextInt(1000);
System.out.println("Fetch get " + i);
account.get(i);
System.out.println(account);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
public class Save implements Runnable {
private Account account;
private Random r = new Random();
public Save(Account a){
account = a;
}
@Override
public void run() {
if(account != null){
int i = 0;
while(true){
try {
TimeUnit.MILLISECONDS.sleep(r.nextInt(1000));
i = r.nextInt(1000);
System.out.println("Save put " + i);
account.put(i);
System.out.println(account);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
public class Test {
public static void main(String[] args) {
Account a = new Account("1");
new Thread(new Save(a)).start();
new Thread(new Fetch(a)).start();
}
}
追问
大哥能不能把JAVA和class文件发我由箱 381932611 谢谢大哥!!
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询