博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
bio伪异步防止服务端线程过多创建
阅读量:6963 次
发布时间:2019-06-27

本文共 1397 字,大约阅读时间需要 4 分钟。

hot3.png

原理:当多个客户端对服务器发起请求时。使用线程池管理服务端阻塞解除后(开始通讯)对业务处理逻辑频繁开启新的任务线程。

public class Server {	final static int PORT = 8765;	public static void main(String[] args) {		ServerSocket server = null;		BufferedReader in = null;		PrintWriter out = null;		try {			server = new ServerSocket(PORT);			System.out.println("server start");			Socket socket = null;			HandlerExecutorPool executorPool = new HandlerExecutorPool(50, 1000);			while(true){				socket = server.accept();				executorPool.execute(new ServerHandler(socket));			}					} catch (Exception e) {			e.printStackTrace();		} finally {			if(in != null){				try {					in.close();				} catch (Exception e1) {					e1.printStackTrace();				}			}			if(out != null){				try {					out.close();				} catch (Exception e2) {					e2.printStackTrace();				}			}			if(server != null){				try {					server.close();				} catch (Exception e3) {					e3.printStackTrace();				}			}			server = null;						}	}}

线程池配置如下:

采用无界队列的方式创建自定义线程池

public class HandlerExecutorPool {	private ExecutorService executor;	public HandlerExecutorPool(int maxPoolSize, int queueSize){		this.executor = new ThreadPoolExecutor(				Runtime.getRuntime().availableProcessors(),				maxPoolSize, 				120L, 				TimeUnit.SECONDS,				new ArrayBlockingQueue
(queueSize)); } public void execute(Runnable task){ this.executor.execute(task); } }

 

转载于:https://my.oschina.net/2286252881/blog/865222

你可能感兴趣的文章
中小型企业网络构建之路由的简单配置
查看>>
Create an inbound email action
查看>>
oracle教程之DML事务锁定的机制
查看>>
Oracle RMAN 维护(一)--RMAN的维护
查看>>
centos6.6关闭防火墙和selinux
查看>>
JAVA RMI远程方法调用简单实例
查看>>
Citrix桌面虚拟化解决方案介绍
查看>>
WCF学习2
查看>>
python之潜心研究多线程(thread模块) 建议使用threading模块
查看>>
阵列无法解挂导致VCS双机倒换失败
查看>>
ORACLE中用for in 使用cursor
查看>>
Apache - AH00451
查看>>
vim使用技巧
查看>>
nagios+centreon监控构建
查看>>
bootstrap-data-target触发模态弹出窗元素
查看>>
3.第一个MyBatis程序_进化
查看>>
获得ios屏幕上的像素
查看>>
FTPS(下)
查看>>
一个合格的运维工程师应该具有的素质
查看>>
字符串与 集合
查看>>