wo317458719 于 2016.03.22 23:10 提问

``````public class Banck {
private Double[] accounts;
public Banck(int n,Double inintPrice) {
accounts= new Double[n];
for(int i=0;i<n;i++){
accounts[i]=inintPrice;
}
}

public  void transfer(Integer from,Integer to,Double mouny) throws InterruptedException{
synchronized(accounts){
while(accounts[from]<mouny){
return;
}
accounts[from]-=mouny;
System.out.printf(" 金额 %10.2f 从账户  %d 到  %d",mouny,from,to);
accounts[to]+=mouny;
System.out.printf(" 总金额 %10.2f",getTotal());
System.out.println();
}
}

public  Double getTotal() throws InterruptedException{
double total=0d;
synchronized(accounts){
for( int i=0;i<accounts.length;i++){
total+=accounts[i];
}
}
}
public int size(){
return accounts.length;
}
public Double[] getAccounts() {
return accounts;
}

public void setAccounts(Double[] accounts) {
this.accounts = accounts;
}

}
``````

#############################
public class TransferRunnable implements Runnable{
private Banck banck;
private Double amount;
private int fromBank;
public TransferRunnable(Banck bank,int from , Double amount){
this.banck=bank;
this.fromBank=from;
this.amount=amount;
}
@Override
public void run() {
synchronized(this){
while(true){
int toBanck=(int)(banck.size()*Math.random());
Double mouny=amount*Math.random();
try {
banck.transfer(fromBank, toBanck, mouny);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
System.out.println("---"+banck.getTotal());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public Banck getBanck() {
return banck;
}
public void setBanck(Banck banck) {
this.banck = banck;
}
public int getFromBank() {
return fromBank;
}
public void setFromBank(int fromBank) {
this.fromBank = fromBank;
}
public Double getAmount() {
return amount;
}
public void setAmount(Double amount) {
this.amount = amount;
}

``````}
``````

############################################

``````public static void main(String[] args) {
Banck b=new Banck(10,100d);
for(int i=0;i<b.size();i++){
TransferRunnable tr=new TransferRunnable(b,i,100d);
t.start();
}
}

}
``````

---1000.0

---1000.0

---1000.0

---1000.0

---1000.0000000000001

---1000.0
---1000.0

---1000.0

---999.9999999999999

---999.9999999999999

---999.9999999999999
---999.9999999999999

2个回答

devmiao      2016.03.22 23:56

wojiushiwo945you      2016.03.23 11:40

`````` @Override
public void run() {
synchronized (banck) {
}
}
``````