2014-02-14 56 views
0

作爲多線程和服務器/客戶端通信的練習,我正在模擬銀行帳戶上的操作。服務器意外地停止讀取客戶端消息

下面的代碼工作,直到銀行有足夠的錢用於客戶的請求。然後,例如,如果銀行中有7美元,而客戶(班員)要求10美元,則服務器用一個字符串響應:「線程#無法獲得這筆錢」,因爲它應該是。問題出在這條信息被打印出來之後,我的服務器類將不會對任何類型的後續請求作出響應:或者高於或低於銀行擁有的金額。

public class BankServer { 
public static void main(String[] args) { 
    try { 
     BankServer bankServer=new BankServer(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 

public BankServer() throws IOException{ 
    account=new BankAccount(); 
    ss=new ServerSocket(PORT); 
    while(!account.isEmpty()){ 
     Socket client=ss.accept(); 
     new Thread(new ConnectionHandler(client,account)).start(); 
     numberOfThreads++; 
    } 
} 

private int numberOfThreads=0; 
private BankAccount account; 
private final static int PORT=8189; 
private ServerSocket ss;} 

中的錢存放建成這樣的BankAccount類:

public class BankAccount { 
public BankAccount(){ 
    amount=100; 
} 

public boolean getMoney(int qnt){ 
    lock.lock(); 
    if(qnt>amount){ 
     System.out.println(Thread.currentThread()+" could not get this amount of money: $"+qnt+"."); 
     return false; //the bank doesn't have enough money to satisfy the request 
    } 
    System.out.println(Thread.currentThread()+" got his money: $"+qnt+"."); 
    amount-=qnt; 
    lock.unlock(); 
    return true; 
} 

public boolean isEmpty() { 
    lock.lock(); 
    System.out.println("Money in the bank: "+amount+"."); 
    if(amount<=0){ 
     lock.unlock(); 
     return true; 
    } 
    lock.unlock(); 
    return false; 
} 

private int amount; 
private ReentrantLock lock=new ReentrantLock();} 

螞蟻,這是ConnectionHandler,我用它來管理從用戶到每一個連接類銀行。

+1

的第一if不知道什麼是'lock',但你沒有解鎖它在'getMoney'方法的第一個'if'中 – BackSlash

+0

謝謝。我可能會犯的最愚蠢的錯誤。再次感謝! – Andrew

+0

不客氣!我發佈了一個答案 – BackSlash

回答

1

我不知道什麼是lock,但你沒有解鎖它在getMoney方法

相關問題