在上一次的基础上做了改动,基于NIO的方式,使用了ThreadPoolExecutor线程池
public void acceptWait() {
try {
serverSocketChannel = ServerSocketChannel.open();
//设置非阻塞
serverSocketChannel.configureBlocking(false);
serverSocketChannel.bind(new InetSocketAddress(port));
selector = Selector.open();
serverSocketChannel.register(selector,SelectionKey.OP_ACCEPT);
} catch (IOException e) {
e.printStackTrace();
}
//工作队列
ArrayBlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
//线程池的基本大小,即在没有任务需要执行的时候线程池的大小
int corePoolSize = 10;
//线程池中允许的最大线程数
int maximumPoolSize = 50;
//空闲线程存活时间
long keepAliveTime = 100L;
//时间单位
TimeUnit unit = TimeUnit.SECONDS;
//拒绝策略
RejectedExecutionHandler rejectionStrategy = new ThreadPoolExecutor.DiscardOldestPolicy();
ThreadPoolExecutor tpe = new ThreadPoolExecutor(corePoolSize,
maximumPoolSize,keepAliveTime,unit,workQueue, Executors.defaultThreadFactory(),rejectionStrategy);
while (true) {
try {
//阻塞1秒
selector.select(1000);
Set<SelectionKey> selectionKeys = selector.selectedKeys();
Iterator<SelectionKey> iterator = selectionKeys.iterator();
while (iterator.hasNext()){
SelectionKey key = iterator.next();
if (key.isAcceptable()) {
SocketChannel socketChannel = serverSocketChannel.accept();
if(socketChannel != null){
socketChannel.configureBlocking(false);
socketChannel.register(selector,SelectionKey.OP_READ);
}
}else if(key.isReadable()){
SocketChannel channel = (SocketChannel) key.channel();
//处理过程中,先取消selector对应连接的注册,避免重复
key.cancel();
channel.configureBlocking(true);
tpe.execute(new RequestHandler(channel.socket()));
}
iterator.remove();
}
//
selector.selectNow();
} catch (IOException e) {
e.printStackTrace();
continue;
}
}
}