线程池未创建所需的线程数

时间:2019-11-08 20:15:36

标签: java sockets threadpool executorservice

在下面的代码中,我使用线程池为套接字服务器和客户端编写了代码,但是我的问题是为客户端创建了一个具有单个线程的线程池,而不是从结果中显示出3个线程。 / p>

当客户端向服务器发送消息时,将显示结果。

代码实现的结果

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 个答案:

答案 0 :(得分:1)

在循环外创建一次池(执行程序)。然后在循环内创建任务实例(可运行),并将其交给池执行。

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