对比Nio时顺带产物,Bio有明显的劣势
package bio;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.ServerSocket;import java.net.Socket;import java.util.concurrent.ArrayBlockingQueue;import java.util.concurrent.ExecutorService;import java.util.concurrent.ThreadPoolExecutor;import java.util.concurrent.TimeUnit;import java.util.logging.Level;import java.util.logging.Logger;public class BioTimeServer { public static void main(String[] args) throws Exception { oneToOneThread(); // 启动线程一对一服务模型 threadPool(); // 启动线程池模型 } /** * 线程池模式,限制了并发线程数和最大池连接数,资源可控不会宕机,但也没有摆脱并发性能问题 * @throws Exception */ public static void threadPool() throws Exception { ServerSocket server = new ServerSocket(9998); TimeServerHandlerExecutePool singleExecutor = new TimeServerHandlerExecutePool(50, 10000); while (true) { System.out.println("Waiting for client... "); Socket socket = server.accept(); singleExecutor.execute(new Thread(new ProcThread(socket))); } } /** * 普通接收方式,一个线程对应一个客户端连接,但资源不可控,数千并发甚至可能导致宕机 * @throws Exception */ public static void oneToOneThread() throws Exception { ServerSocket server = new ServerSocket(9999); while (true) { System.out.println("Waiting for client... "); Socket socket = server.accept(); new Thread(new ProcThread(socket)).start(); } }}class TimeServerHandlerExecutePool { private ExecutorService executor; public TimeServerHandlerExecutePool(int maxPoolSize, int queueSize) { executor = new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors(), maxPoolSize, 120L, TimeUnit.SECONDS, new ArrayBlockingQueue<>(queueSize)); } public void execute(Runnable task) { executor.execute(task); }}class ProcThread implements Runnable { private Socket conn; public ProcThread(Socket conn) { this.conn = conn; } @Override public void run() { InputStream is; OutputStream os; try { is = conn.getInputStream(); os = conn.getOutputStream(); int bytesRead = 0; byte[] buffer = new byte[8192]; while ((bytesRead = is.read(buffer)) != -1) { System.out.println(new String(buffer, 0, bytesRead)); os.write("copy that.\r\n".getBytes()); os.flush(); } } catch (IOException ex) { Logger.getLogger(ProcThread.class.getName()).log(Level.SEVERE, null, ex); } finally { try { conn.close(); } catch (IOException ex) { Logger.getLogger(ProcThread.class.getName()).log(Level.SEVERE, null, ex); } conn = null; } }}