Java 服务器意外停止读取客户端消息

Java 服务器意外停止读取客户端消息,java,multithreading,locking,client,Java,Multithreading,Locking,Client,作为多线程和服务器/客户端通信的练习,我正在模拟银行帐户上的操作 下面的代码一直有效,直到银行里有足够的钱来满足客户的请求。然后,例如,如果银行里有7美元,而一个客户(类出纳员)要求10美元,服务器会用一个字符串响应:“Thread#cannot get this mound money”,这是应该的。问题是,在打印出此消息后,我的服务器类将不会响应任何类型的后续请求:高于或低于银行拥有的金额 public class BankServer { public static void main(S

作为多线程和服务器/客户端通信的练习,我正在模拟银行帐户上的操作

下面的代码一直有效,直到银行里有足够的钱来满足客户的请求。然后,例如,如果银行里有7美元,而一个客户(类出纳员)要求10美元,服务器会用一个字符串响应:“Thread#cannot get this mound money”,这是应该的。问题是,在打印出此消息后,我的服务器类将不会响应任何类型的后续请求:高于或低于银行拥有的金额

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();}
公共类银行账户{
公共银行账户(){
金额=100;
}
公共布尔getMoney(int-qnt){
lock.lock();
如果(qnt>金额){
System.out.println(Thread.currentThread()+“无法获取此金额:$”+qnt+);
return false;//银行没有足够的钱来满足请求
}
System.out.println(Thread.currentThread()+“得到他的钱:$”+qnt+);
金额-=qnt;
lock.unlock();
返回true;
}
公共布尔值为空(){
lock.lock();
System.out.println(“银行存款:+金额+”);

if(amount我不知道什么是
lock
,但是在
getMoney
方法的第一个
if
中没有解锁它

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;
}

我不知道什么是
lock
,但是在
getMoney
方法的
if
中,你没有解锁它。谢谢。这是我可能犯的最愚蠢的错误。再次感谢!不客气!我发布了答案