Java网络编程BS架构+线程池优化

服务

import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.*;

public class Server3 {
    public static void main(String[] args) throws  Exception {
        ServerSocket serverSocket = new ServerSocket(7777);

        //创建线程池对象
        ExecutorService pool =  new ThreadPoolExecutor(16*2,
                16*2,
                0,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(8),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());//线程池满了的拒绝策略
            while (true){
                Socket socket = serverSocket.accept();
                pool.execute(new HttpServer(socket));
            }
    }
}

实现Runnable类

import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;

public class HttpServer implements Runnable {
    private Socket socket;
    public HttpServer (Socket socket){
        this.socket = socket;
    }


    @Override
    public void run(){
        try{
            OutputStream os = socket.getOutputStream();
            PrintStream ps = new PrintStream(os);
            ps.println("Http/1.1 200 ok");
            ps.println("Content-Type:text/html; charset=utf-8");
            ps.println();
            ps.println("你好");
            ps.close();
            socket.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

效果:

Java网络编程BS架构+线程池优化_第1张图片

你可能感兴趣的:(java,网络,架构)