gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 13:26:38 24 4
gpt4 key购买 nike

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

下面的代码将一直有效,直到银行中有足够的资金来满足客户的请求。然后,例如,如果银行里有 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();}

这就是 ConnectionHandler,我用这个类来管理从用户到银行的每个连接。

最佳答案

我不知道什么是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;
}

关于java - 服务器意外停止读取客户端消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21785925/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com