线程池处理
在Netty学习之路(1)中,使用的处理方式是每个客户端连接创建一个独立线程去处理的方式,这篇中,将采用线程池的处理方式。但由于也是堵塞式,所以也有存在大量的弊端。具体利弊这里就不再阐述,自行脑补或者找度娘谷哥。
上代码
server端:
package com.netease.bio_2;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
/*
* 线程池处理
*
* */
public class Server {
public static void main(String[] args) {
ServerSocket ss = null;
try {
ss = new ServerSocket(8888);
System.out.println("服务器已启动:");
while(true){
ServerHandlePool pool = new ServerHandlePool(50, 100);
Socket socket = ss.accept();
pool.execute(new ServerHandle(socket));
}
} catch (IOException e) {
e.printStackTrace();
}
Runtime.getRuntime().addShutdownHook(new Thread(){
public void run(){
System.out.println("-----Hook execute ------");
}
});
}
}
线程池:
package com.netease.bio_2;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ServerHandlePool {
private ExecutorService executor;
public ServerHandlePool(int maximumPoolSize,int maxQueuesize){
executor = new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors(), maximumPoolSize, 120L, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(maxQueuesize));
}
public void execute(Runnable task){
executor.execute(task);
}
}
客户端代码和服务器端处理类代码和(1)中没有变化,这里不再占用篇幅了。
这里简单说下核心代码:
new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors(), maximumPoolSize, 120L, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(maxQueuesize));
参照JDKAPI
构造方法:
ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue)
availableProcessors方法是向 Java 虚拟机返回可用处理器的数目。这里corePoolSize 就取处理器的数目。
说下 corePoolSize 和maximumPoolSize的含义
简单理解(没有考虑边界的情况):当线程数量小于corePoolSize 时,有新任务过来的时候就直接在线程池里创建。
当当前线程数不少于corePoolSize 时但是少于maximumPoolSize,则将线程放入队列中等待处理。也就是说线程队列满的时候,才会创建,但是,当corePoolSize 等于maximumPoolSize,那再来新线程就直接拒绝了。
这里就要谈到这个keepAliveTime,当一些任务执行完毕,进入空闲状态时,当超过keepAliveTime这个时间就会被释放出来。
BlockingQueue是一个接口,代码里使用的 ArrayBlockingQueue
查看API,有说明,copy一下
一个由数组支持的有界阻塞队列。此队列按 FIFO(先进先出)原则对元素进行排序。