Пул потоков не создает желаемого количества потоков - PullRequest
0 голосов
/ 08 ноября 2019

В приведенном ниже коде я пишу код для сокет-сервера и клиента, используя Thread Pool, но моя проблема в том, что для клиента создается пул потоков с одним потоком, а не 3 потока, как это видно из результата.

Результат появляется, когда клиенты отправляют сообщение на сервер.

Результат для реализации кода

name Thread: pool-1-thread-1
name Thread: pool-2-thread-1
name Thread: pool-3-thread-1

Я хочу, чтобы результат был таким

name Thread: pool-1-thread-1
name Thread: pool-1-thread-2
name Thread: pool-1-thread-3

исходный код для сервера

package testThreadPool;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


public class TCPServer2 {

    private static ServerSocket servSock;
    private static final int PORT = 1234;


    public static void main(String[] args) {

        System.out.println("Connecting to port......\n");
        try {
            servSock = new ServerSocket(PORT); // step 1
        } catch (IOException e) {
            System.out.println("Unable to connect to PORT 1234");
            System.exit(1);
        }

        do {

            Socket link = null;
            try {
                link = servSock.accept();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            ExecutorService executor = Executors.newFixedThreadPool(5);
            Runnable threadpool = new newClient2(link, "serverThread");
            executor.execute(threadpool);

        }
         while(true);

    }
}


class newClient2 implements Runnable {

        private Scanner input;
        private PrintWriter output;
        private Socket link;
        private String name;

        public newClient2(Socket socket, String SerName) {
            link = socket;
            name = SerName;

             try {
                input = new Scanner(link.getInputStream());
                 output = new PrintWriter(link.getOutputStream(), true);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        public void run() {


            int numMessages = 0;
            String message = input.nextLine(); // step 4

            try {

               while(!message.equals("***CLOSE***")) {
                //System.out.println("message recieved.");
                numMessages++;              
                output.println("Message " + numMessages + " : " + message); // step 4
                System.out.println("name Thread: " + Thread.currentThread().getName());
                 message = input.nextLine(); // step 4
               }

            }
            finally{

                try {
                    System.out.println("\n* Closing connection....");
                    link.close(); // step 5
                } catch (IOException e) {
                    System.out.println("Unable to disconnect!.....");
                    System.exit(1);
                }
            }

        }

    }




исходный код для клиента

package testThreadPool;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class TCPClient2 {

    private static InetAddress host;
    private static final int PORT = 1234;

    public static void main(String[] args) {
       try {
        host = InetAddress.getLocalHost();
    } catch (UnknownHostException e) {
        System.out.println("HOST Not found!");
        System.exit(1);
    }
       accessServer();
    }

    private static void accessServer() {
        Socket link = null; //step 1

        try {
            link = new Socket(host, PORT);//Step 1
            Scanner input = new Scanner(link.getInputStream()); // Step 2
            PrintWriter output = new PrintWriter(link.getOutputStream(), true); // step 2

            Scanner userEntry = new Scanner(System.in);
            String message, response;

            do {
                System.out.print("Enter message: ");
                message = userEntry.nextLine();
                //message = "hello Im client";
                output.println(message); // Step 3
                response = input.nextLine(); // step 3

                System.out.println("\n SERVER> " + response);
            }
             while(!message.equals("***CLOSE***"));

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        finally {
            try {
                System.out.println("\n* Closing connection......");
                link.close(); //step 4
            } catch (IOException e) {
                System.out.println("Unable to disconnect!");
                System.exit(1);
            }
        }
    }

}



1 Ответ

1 голос
/ 09 ноября 2019

Создайте пул (исполнитель) один раз за пределами цикла. Затем создайте экземпляры задачи (runnable) внутри цикла и передайте их в пул для выполнения.

ExecutorService pool = Executors.newFixedThreadPool(5);
do {

    Socket link = null;
    try {
        link = servSock.accept();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    Runnable task = new newClient2(link, "serverThread");
    pool.execute(task);

}
while (true);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...