我正在开发一个简单的邮件服务器,以学习如何在Java中使用套接字。 为了处理多个请求,我使用以下解决方案:
while(true){
if(currentThread == -1){
currentThread++;
connectionThreads.add(new ConnectionThread(serverSocket));
connectionThreads.get(currentThread).setDaemon(true);
connectionThreads.get(currentThread).start();
System.out.println("STARTED thr " + currentThread);
}
if(connectionThreads.get(currentThread).isConnected()){
System.out.println("THREAD CONNECTED: Thr " + currentThread);
currentThread++;
connectionThreads.add(new ConnectionThread(serverSocket));
connectionThreads.get(currentThread).setDaemon(true);
connectionThreads.get(currentThread).start();
System.out.println("STARTED thr " + currentThread);
}
}
其中“ currentThread”是整数,connectionThreads是客户端套接字的ArrayList,serverSocket是所有客户端套接字绑定到的服务器套接字。 问题是,当我将客户端连接到服务器时,它在第一个/第二个线程中运行良好,然后卡住了: 视频输出为:
STARTED thr 0
THREAD CONNECTED: Thr 0
STARTED thr 1
但是,如果我添加以下else语句:
while(true){
if(currentThread == -1){
currentThread++;
connectionThreads.add(new ConnectionThread(serverSocket));
connectionThreads.get(currentThread).setDaemon(true);
connectionThreads.get(currentThread).start();
System.out.println("STARTED thr " + currentThread);
}
if(connectionThreads.get(currentThread).isConnected()){
System.out.println("THREAD CONNECTED: Thr " + currentThread);
currentThread++;
connectionThreads.add(new ConnectionThread(serverSocket));
connectionThreads.get(currentThread).setDaemon(true);
connectionThreads.get(currentThread).start();
System.out.println("STARTED thr " + currentThread);
}else System.out.println(currentThread + " isConnected " + connectionThreads.get(currentThread).isConnected());
}
它工作正常。
谁能告诉我发生了什么事?
谢谢! :-)