伪NIO编程,利用线程池改进BIO

版权声明:本文为博主原创文章,未经博主允许不得转载。转载请注明出处,并告知本人 https://blog.csdn.net/the_conquer_zzy/article/details/83114313

利用线程池改进请求和线程的1:1所带来的大量连接所带来的大量线程创建问题。

伪NIO TimeServer源码

public class MockTimeServer {
    public static void main(String[] args){

        int port=9001;
        if(args!=null&&args.length>0){
            port=Integer.parseInt(args[0]);
        }

        ServerSocket server=null;

        try {
            server=new ServerSocket(port);

            System.out.println("The time Server is start in port: "+port);
            Socket socket=null;
            TimeServerHandlerExecutePool executor=new TimeServerHandlerExecutePool(50,10000);
            while(true){
                socket=server.accept();

                executor.execute(new TimeServerHandler(socket));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(server!=null){
                System.out.println("The time server close");
                try {
                    server.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                server=null;
            }
        }
    }
}

线程池:

public class TimeServerHandlerExecutePool {

    private ExecutorService executorService;

    public TimeServerHandlerExecutePool(int maxPoolSize, int queueSize) {
        executorService=new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors(),maxPoolSize,120L, TimeUnit.SECONDS,new ArrayBlockingQueue<Runnable>(queueSize));

    }

    public void execute(Runnable task){
        executorService.execute(task);
    }
    ```

客户端代码:

public class TimeClient {

public static void main(String[] args){
    int port=9001;

    if(args!=null&&args.length>0){

        port=Integer.parseInt(args[0]);
    }


    BufferedReader in=null;

    PrintWriter out=null;

    try {
        try(Socket socket=new Socket("127.0.0.1",port)){

            in=new BufferedReader(new InputStreamReader(socket.getInputStream()));

            out=new PrintWriter(socket.getOutputStream(),true);

            out.println("Query Time Order");
            System.out.println("Send order to server succeed.");
            String resp=in.readLine();

            System.out.println("Now the time is: "+resp);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

}

展开阅读全文

没有更多推荐了,返回首页