服务
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;}@Overridepublic 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();}}
}
效果: