java - 线程池未创建所需数量的线程

标签 java sockets threadpool executorservice

在下面的代码中,我使用线程池为套接字服务器和客户端编写代码,但我的问题是为客户端创建了一个具有单个线程的线程池,而不是 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);
            }
        }
    }

}



最佳答案

在循环外创建池(执行器)。然后在循环内创建任务(可运行)实例,并将它们交给池子执行。

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

关于java - 线程池未创建所需数量的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58773232/

相关文章:

C# 套接字忽略我的 SendTimeout 值

Python:无法使用 SSL 套接字发出 HTTPS 请求

asp.net - 对这个操作使用线程本地存储安全吗?

java - 缺少 Android JRE 系统库 (java.awt.*)

java读取csv+子数组的特定总和-最有效的方法

java - BufferedReader.read() 占用 100% 的 CPU

c# - HttpClient.PostAsync ThreadPool 中没有足够的空闲线程来完成操作

c# - 使用 SmartThreadPool MaxThreads=5 仍然看到更多

java - 树莓派上的数据库

java - 无法通过 AssetManager - libgdx 从 zip 存档加载 TextureAtlas