服务器端请求的Java线程ArrayList

时间:2020-02-16 17:22:22

标签: java sockets serversocket

我正在开发一个简单的邮件服务器,以学习如何在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());
        }

它工作正常。

谁能告诉我发生了什么事?

谢谢! :-)

0 个答案:

没有答案