作为多线程和服务器/客户端通信的练习,我正在模拟银行账户的操作。
以下代码一直有效,直到银行有足够的资金用于客户提出的请求。然后,例如,如果银行中有7美元并且客户(类Teller)要求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();}
Ant这是ConnectionHandler,我用它来管理从用户到银行的每一个连接。
答案 0 :(得分:1)
我不知道lock
是什么,但你没有在if
方法的第一个getMoney
解锁它
public boolean getMoney(int qnt){
lock.lock();
if(qnt>amount){
System.out.println(Thread.currentThread()+" could not get this amount of money: $"+qnt+".");
//unlock here?
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;
}