62,614
社区成员
发帖
与我相关
我的任务
分享
package com.briup.ch10;
public class Account {
private long no;
private double balance;
synchronized public String deposit(double amount){
String msg="";
if(amount<0){
msg="sorry,amount not right.";
}else{
balance=balance+amount;
msg=Thread.currentThread().getName()+" earn"+amount+" and balance has"+balance;
notifyAll();
}
return msg;
}
synchronized public String withdraw(double amount){
String msg="";
while(amount<0||amount>balance){
msg="sorry,amount not right.";
try{
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
balance=balance-amount;
msg=Thread.currentThread().getName()+" withdraw"+amount+" and balance has"+balance;
return msg;
}
}
存钱的
package com.briup.ch10;
public class Boys extends Thread{
private Account account;
public Boys(Account account,String name){
this.account=account;
setName(name);
start();
}
public void run(){
while(true){
long amount=(long)(Math.random()*10000);
String msg=account.deposit(amount);
System.out.println(msg);
try{
sleep(amount);
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
}
取钱的
package com.briup.ch10;
public class Girls implements Runnable{
private Account account;
public Girls(Account account,String name){
Thread t=new Thread(this);
this.account=account;
t.setName(name);
t.start();
}
public void run(){
while(true){
long amount=(long)(Math.random()*10000);
String msg=account.withdraw(amount);
System.out.println(msg);
try{
Thread.currentThread().sleep(amount);
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}
测试
package com.briup.ch10;
public class ATM{
public static void main(String[] args) {
Account account=new Account();
Thread t1=new Boys(account,"tony");
new Girls(account,"lucy");
new Girls(account,"track");
}
}