當前位置:編程學習大全網 - 編程語言 - 程序庫

程序庫

這需要線程。

這是代碼

//銀行類

公共類銀行

{

私人期末雙[]賬戶;

公共銀行(int n,double initBalance)

{

accounts = new double[n];

for(int I = 0;我& lt帳戶.長度;i++)

{

accounts[I]= init balance;

}

}

公共同步void傳輸(int from,int to,double amount)引發InterruptedException

{

if(帳戶[from]& lt;金額)

{

wait();

}

system . out . println(thread . current thread());

賬戶[從] -=金額;

system . out . printf(" % 10.2 f from % d to % d ",金額,從,到);

帳戶[從]+=金額;

system . out . printf(" Total b ance:% 10.2 f % n ",getTotalBalance());

notify all();

}

私有同步對象getTotalBalance()

{

double sum = 0;

用於(雙賬戶)

{

sum+= AC;

}

返回總和;

}

public int size()

{

返回帳戶。長度;

}

}

//線程函數

公共類TransferRunnable實現Runnable

{

私人銀行銀行;

private int fromAc

私有雙倍maxAmt

私有int delay = 10;

公共轉賬Runnable(銀行Bank,int fromAC,double maxAmt)

{

super();

this.bank = bank

this.fromAc = fromAc

this.maxAmt = maxAmt

}

@覆蓋

公共無效運行()

{

while(真)

{

嘗試

{

int toAc =(int)(bank . size()* math . random());

double AMT = maxAmt * math . random();

銀行轉帳(fromAc,toAc,AMT);

thread . sleep((int)(delay * math . random());

}

catch(中斷異常e)

{

// TODO自動生成的catch塊

e . printstacktrace();

}

}

}

}

//測試類

公共課考試

{

/**

* @param args

*/

公共靜態void main(String[] args)

{

銀行b =新銀行(10,10000);

for(int I = 0;我& lt10;i++)

{

TransferRunnable r = new TransferRunnable(b,0,10000);

螺紋t =新螺紋(r);

t . start();

}

}

}

  • 上一篇:有什麽好玩的足球經理類的手機遊戲嗎?
  • 下一篇:樂高死黨斯蒂芬妮的生日歌叫什麽?
  • copyright 2024編程學習大全網